Reputation:
I have the following java code:
String strTest = null;
for (AlternativeEntity alternativeEntity : msg.Guidance()
.getAlternatives()) {
strTest = strTest + alternativeEntity.getArrivalStation().getName() + ", ";
}
The output looks like this:
nullabc, xyz, oop,
How can I solve this problem and very bad character format? It would be great if I can create output like this:
abc, xyz, oop
Upvotes: 0
Views: 144
Reputation: 7008
Java provides StringBuilder class just for this purpose,its simple and easy to use..
StringBuilder str = new StringBuilder("India ");
//to append "Hi"
str.append("Hi");
// print the whole string
System.out.println("The string is "+str)
the output will be : The string is India Hi
click here to know more about StringBuilder class
Upvotes: 1
Reputation: 62864
You can use Guava's Joiner#join(Iterable parts). For example:
Joiner joiner = Joiner.on(", ").skipNulls();
String result = joiner.join(list);
System.out.println(result);
Here, all the elements of the list will be printed comma separated without any trailing commas. Also, all the null
elements will be skipped.
More info:
Upvotes: 3
Reputation: 46960
String strTest = null;
for (AlternativeEntity alternativeEntity : msg.Guidance().getAlternatives()) {
String name = alternativeEntity.getArrivalStation().getName();
strTest = (strTest == null) ? name : strTest + ", " + name;
}
If the list is long, you should use a StringBuilder
rather than the String
for strTest
because the code above builds a fresh string on each iteration: far too much copying.
Upvotes: 0
Reputation: 21961
Initialize strTest
as:
String strTest = "";
Also, remove the last comma ,
strTest=strTest.substring(0, strTest.length()-1);
Upvotes: 3
Reputation: 639
Initialize String strTest="";
For skipping the last comma',' Use outside For loop:
strTest = strTest.substring(0,strTest.trim().length()-1);
Upvotes: 0
Reputation: 7501
Initialize your string to "":
String strTest = "";
Alternatively, you should use a StringBuilder:
StringBuilder builder = new StringBuilder();
for (AlternativeEntity alternativeEntity : msg.Guidance()
.getAlternatives()) {
builder.append(alternativeEntity.getArrivalStation().getName()).append(", ");
}
This will produce better performance.
Upvotes: 3
Reputation: 7854
why don't you use:
String strTest = "";
and at the end:
if(strTest.endsWith(", "))
strTest = strTest.substring(0, strTest.length()-2);
Upvotes: 0