I have an ArrayList with some Strings. I want to store that list of numbers from the ArrayList in a single string separated by a comma like the following.
String s = "350000000000050287,392156486833253181,350000000000060764"
This is my list:
List<String> e = new ArrayList<String>();
e.add("350000000000050287");
e.add("392156486833253181");
e.add("350000000000060764");
I have been trying to do it the following way:
StringBuilder s = new StringBuilder();
for (String id : e){
s.append(id+",");
}
The only problem with this is that this adds a comma to the end and I do not want that.What would be the best way to this?
Thanks
The easiest solution is to use String.join:
List<String> list = new ArrayList<String>();
list.add("11");
list.add("22");
list.add("33");
String joined = String.join(",", list);
System.out.println(joined);
//prints "11,22,33"
Note that this requires Java 8.
However if you want to support older versions of Java, you could fix your code using an iterator:
StringBuilder sb = new StringBuilder();
Iterator<String> iterator = list.iterator();
// First time (no delimiter):
if (iterator.hasNext()) {
sb.append(iterator.next());
// Other times (with delimiter):
while (iterator.hasNext()) {
sb.append(",");
sb.append(iterator.next());
}
}
Or simply use a boolean to determine the first time:
StringBuilder sb = new StringBuilder();
boolean firstTime = true;
for (String str : list) {
if (firstTime) {
firstTime = false;
} else {
sb.append(",");
}
sb.append(str);
}
But the latter should obviously be less performant than using an iterator comparing the generated bytecode per method. However, this might not be true as Tagir Valeev pointed out: this benchmark shows us that using a flag is more performant with a number of iterations starting from 10.
If anyone could explain why this is the case, I'd be glad to know.