The simplest 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);
Please note that this requires Java 8.
However, if you want to support older versions of Java, you can fix your code with 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 just use a boolean to determine for 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 be clearly less productive than using an iterator comparing the generated bytecode for each method. However, this may not be true, as Tagir Valeev pointed out: this benchmark shows us that using the flag is more indicative with the number of iterations starting at 10.
If anyone could explain why this is so, I would be happy to know.
source share