[java] Join String list elements with a delimiter in one step

Is there a function like join that returns List's data as a string of all the elements, joined by delimiter provided?

 List<String> join; ....
 String join = list.join('+");
 // join == "Elem 1+Elem 2";

or one must use an iterator to manually glue the elements?

This question is related to java

The answer is


If you just want to log the list of elements, you can use the list toString() method which already concatenates all the list elements.



If you are using Spring you can use StringUtils.join() method which also allows you to specify prefix and suffix.

String s = StringUtils.collectionToDelimitedString(fieldRoles.keySet(),
                "\n", "<value>", "</value>");

You can use : org.springframework.util.StringUtils;

String stringDelimitedByComma = StringUtils.collectionToCommaDelimitedString(myList);

You can use the StringUtils.join() method of Apache Commons Lang:

String join = StringUtils.join(joinList, "+");

Or Joiner from Google Guava.

Joiner joiner = Joiner.on("+");
String join = joiner.join(joinList);