Long string concatenation problem in java? [closed] - java

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
When I am trying to concatenate strings in Java like so:
COsavedform = vtd + "," + stricode + "," + striname+ ","
+ striqty + "," + strirate + "," + striamt;
every variable containing some String Value and returns correct value of COsavedform but when I add something more to the same COsavedform like..
COsavedform = vtd+","+ccode.getText()+","+striqty
+ "," + strirate + "," + striamt+","+mode+",Customer";
mode is also a string variable. Then it returns only COsavedform=","+mode+",Customer", only not the entire things.
Problem part of that full code_--
System.out.println("striname:"+striname);
System.out.println("stricode:"+stricode);
System.out.println("striqty:"+striqty);
System.out.println("strirate:"+strirate);
System.out.println("striamt"+striamt);
System.out.println("ccode"+ccode.getText());
System.out.println("mode"+mode);
String Csavedform = vtd + "," + stricode + "," + striname+ "," + striqty + "," + strirate + "," + striamt;
System.out.println("CSaved::"+Csavedform);
//System.out.println("COSaved::"+COsavedform);
String Isavedform = vtd+","+ccode.getText()+","+striqty+","+strirate+","+striamt+","+mode+",Customer";
System.out.println("Item savedforitem::"+Isavedform);
```
Output Generated::
vdt:31/12/2019
striname:Kazu
stricode:kazu
striqty:1.0
strirate:1000.0
striamt1000.0
ccode0001
modePending
CSaved::31/12/2019,kazu,Kazu,1.0,1000.0,1000.0
,Pending,Customer
Output Expected::
vdt:31/12/2019
striname:Kazu
stricode:kazu
striqty:1.0
strirate:1000.0
striamt1000.0
ccode0001
modePending
CSaved::31/12/2019,kazu,Kazu,1.0,1000.0,1000.0
Item savedforitem::31/12/2019,0001,1.0,1000.0,1000.0,Pending,Customer

You can use +=
COsavedform += vtd+","+ccode.getText()+","+striqty + "," + strirate + "," + striamt+","+mode+",Customer";
But better to use StringBuilder
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("str1").append("str2")...
COsavedform = stringBuilder.toString();
because its better for memory

Use concat()
Java string concat() method concatenates multiple strings. This method appends the specified string at the end of the given string and returns the combined string. We can use concat() method to join more than one strings
Edited Answer after comment
There are 4 Ways to concatenate String in Java
Concatenation operator (+)
StringBuffer class
StringBuilder class
String.concat() function
Use + operator to concatenate
String stringA= "Stack";
String stringB = "overflow";
String result = stringA + "," + stringB;
System.out.println(result);
By using StringBuilder
StringBuilder result = new StringBuilder();
result.append(stringA).append(",").append(stringB);
System.out.println(result.toString());
By using StringBuffer
StringBuffer result = new StringBuffer();
sBuffer.append(stringA).append(",").append(stringB);
System.out.println(result.toString());

Related

Convert into Java 8 Lambda expression

I am very new to lambda. Can someone please help in converting following nested loops in lambda -
for (Question question : questionList) {
formattedText += NEW_LINE + localizeString(QUESTION_STRING_ID) + question.getQuestionText();
formattedText += NEW_LINE + localizeString(ANSWER_STRING_ID);
for (Answer answer : question.getAnswers()) {
formattedText += answer.getAnswerText() + NEW_LINE;
}
}
Solution I tried
for (Question question : questionList) {
formattedText += NEW_LINE + localizeString(QUESTION_STRING_ID) + question.getQuestionText();
formattedText += NEW_LINE + localizeString(ANSWER_STRING_ID);
question.getAnswers().forEach(answer -> {formattedText += answer.getAnswerText() + NEW_LINE;});
}
Not sure how can I convert both loops into single lambda expression? Also, this solution is not working since it needs formattedText to be declared as final.
It may be implemented using Collectors.joining collector of Stream API:
String prefixQ = NEW_LINE + localizeString(QUESTION_STRING_ID);
String suffixQ = NEW_LINE + localizeString(ANSWER_STRING_ID);
String result = questionList.stream()
.map(q ->
prefixQ + q.getQuestionText() + suffixQ
+ q.getAnswers().stream()
.map(Answer::getAnswerText)
.collect(Collectors.joining(NEW_LINE))
)
.collect(Collectors.joining(NEW_LINE));
You're looking for a Collector. For example,
for (Question question : questionList) {
formattedText += NEW_LINE + localizeString(QUESTION_STRING_ID) + question.getQuestionText();
formattedText += NEW_LINE + localizeString(ANSWER_STRING_ID);
formattedText +=
question.getAnswers()
.stream()
.map(Answer::getAnswerText)
.collect(Collectors.joining(NEW_LINE));
formattedText += NEW_LINE;
}
That supposes that NEW_LINE represents a String. If instead it is a character then you could use String.valueOf(NEWLINE) as the argument to Collectors.joining().
Do note, however, that there is not actually any lambda in that at all. The one place where one might have been used, I use a method reference instead.

How to separate each declared string in another string by comma in spring mvc?

I am using Spring MVC. I want to separate each declared string in another string by using comma and without using an array. And I need to pass that comma separated string in another Java file.
here is my code:
below is the model having three different setters and getters
public String pk1=getInstitutionId();
public String pk2=getInstitutionName();
public String pk3=getIsoCountryCode();
And Now I want to split this by using comma like this:
private String MultipleprimaryKeyStr= pk1 + "," + pk2 + "," + pk3;
But this pk1, pk2 and pk3 are taking as separate string. But MultipleprimaryKeyStr should take it as variable.
You have to do like
String MultipleprimaryKeyStr= params[0] + "," + params[1] + "," + params[2];
One more thing, I would like to tell you that you should not go in static but you should run while or for loop there like this:
String MultiplePrimaryKeyStr = "";
for(int i = 0; i < params.length; i++)
{
MultiplePrimaryKeyStr = ((i!=0) ? "," : "") + params[i];
}
By doing pk1 + "," + pk2 + "," + pk3 you are creating a new String because the operator + is used for concatenation operation in Strings.
So now you get this new String and you can split this String using split(",") as:
private String MultipleprimaryKeyStr= pk1 + "," + pk2 + "," + pk3;
String[] newStr= MultipleprimaryKeyStr.split(",");
By doing concatenation of multiple string into one string and those string is separated by comma.
Ex. String MultiplePrimaryKeyStr="This, is, separated, string";
just pass this string to new java file. And split in that file by calling split().
String[] sepratedString=MultiplePrimaryKeyStr.split(",");
process that string array inside loop.

Java NewLine "\n" not working in save to text file [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
Here is my code:
public String display() {
return "\n......................\nFixed Employee:\n" +
"Name: " + super.fullName() +
"\nSalary: " + salary() +
" tk\n......................";
}
But when I'm invoking this method from main class, "\n" newLine not working. just showing one line output. Will you plz help to solve the problem?
Thanks
For saving in files use \r\n. \n as new lines is viable on printstreams but not writing to files.
You may need the system independent line separator as it might differ from one OS to another. Just replace the \n with the value of line separator:
I can be retrieve as you load any system property:
public String display() {
String separator = System.getProperty("line.separator"); // Load the system property using its key.
return "\n......................\nFixed Employee:\n"
+ "Name: "
+ super.fullName() +
"\nSalary: "
+ salary()
+ " tk\n......................"
.replace("\\n", separator); // replace the \n before returning your String
}
Or simply use System#lineSeparator method as #Deepanshu Bedi suggested:
public String display() {
String separator = System.lineSeparator(); // Consider it as a shortcut.
return "\n......................\nFixed Employee:\n"
+ "Name: "
+ super.fullName() +
"\nSalary: "
+ salary()
+ " tk\n......................"
.replace("\\n", separator); // replace the \n before returning your String
}

Java empty String split ArrayIndexOutOfBoundsException [duplicate]

This question already has answers here:
Java String split is not working
(3 answers)
Closed 7 years ago.
I have come across an unexpected feature in the split function of String in Java, here is my code:
final String line = "####";
final String[] lineData = line.split("#");
System.out.println("data: " + lineData[0] + " -- " + lineData[1]);
This code gives me an ArrayIndexOutOfBoundsException, whereas I would expect it to print "" and "" (two empty Strings), or maybe null and null (two null Strings).
If I change my code for
final String line = " # # # #";
final String[] lineData = line.split("#");
System.out.println("data: " + lineData[0] + " -- " + lineData[1]);
Then it prints " " and " " (the expected behaviour).
How can I make my first code not throwing an exception, and giving me an array of empty Strings?
Thanks
You can use the limit attribute of split method to achieve this. Try
final String line = "####";
final String[] lineData = line.split("#", -1);
System.out.println("Array length : " + lineData.length);
System.out.println("data: " + lineData[0] + " -- " + lineData[1]);
As always, answer is written in the Javadoc
This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.
Since your array is composed only by empty strings, they are not added to it, thus trying to access the values result in an ArrayOutOfBoundException.
If I understand your question, this would do it -
final String line = " # ";
final String[] lineData = line.split("#");
System.out.println("data: " + lineData[0] + " -- " + lineData[1]);
The problem is that the empty string isn't a character.

Optimize String += or Concat? [duplicate]

This question already has answers here:
String concatenation: concat() vs "+" operator
(12 answers)
Closed 9 years ago.
I am writing a file with possibly 1000 data points. I have classes for all of these and am currently writing all of the data at the end (the datapoints are taken at 1s intervals). What I am currently doing is written below, and it's very slow. Would I be better off changing how I am writing the string/bytes to the file? Or would I be better off writing this information to some file pointer as the application is running?
Btw, all of the things such as getAccuracy() and such are floats/ints (so it has to convert those also).
fileStr = "";
fileStr += "timestamp,Accuracy,Altitude,Latitude,Longitude,GPSSatelliteEntries\r\n";
for (Iterator<Entry> i = entries.iterator(); i.hasNext(); ) {
Entry item = i.next();
long ts = item.getTs();
DataEntry d = item.getD();
List<GPSSatelliteEntry> satellites = item.getG();
// write stuff
fileStr += ts + ",";
fileStr += d.getAccuracy() + "," + d.getAltitude() + "," + d.getLatittude() + "," + d.getLongitude() + ",";
fileStr += "[";
boolean entered = false;
for (Iterator<GPSSatelliteEntry> j = satellites.iterator(); j.hasNext(); ) {
GPSSatelliteEntry item2 = j.next();
entered = true;
fileStr += "(" + item2.getAzimuth() + "," + item2.getElevation() + "," + item2.getPrn() + "," + item2.getSnr() + "),";
}
// chop off extra ,
if (entered)
fileStr = fileStr.substring(0, fileStr.length() - 1);
fileStr += "]";
fileStr += "\r\n";
}
Everytime you have hard work with Strings, use StringBuilder or StringBuffer to achieve better performance .
Don't forget that String is immutable, and each time you modify String new instance will be created and it costs performance.
Most probably string buffer
A thread-safe, mutable sequence of characters. A string buffer is like a String, but can be modified.
or go for string builder
StringBuilder stuff = new StringBuilder();
stuff.append("PUT YOUR STRINGS HERE");
stuff.append("PUT YOUR STRINGS HERE");
Then you can use 'stuff' to print the strings.
Put it in a loop and iterate over a large number with a timer to see the advantages, it's pretty interesting.

Categories