Join String list elements with a delimiter in one step

Java

Java Problem Overview


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?

Java Solutions


Solution 1 - Java

Solution 2 - Java

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

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

Solution 3 - Java

Or Joiner from Google Guava.

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

Solution 4 - Java

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>");

Solution 5 - Java

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

String stringDelimitedByComma = StringUtils.collectionToCommaDelimitedString(myList);

Solution 6 - Java

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionEugenePView Question on Stackoverflow
Solution 1 - JavagahraeView Answer on Stackoverflow
Solution 2 - JavaRomain LinsolasView Answer on Stackoverflow
Solution 3 - JavanandaView Answer on Stackoverflow
Solution 4 - JavamarcelloView Answer on Stackoverflow
Solution 5 - JavaKarim OukaraView Answer on Stackoverflow
Solution 6 - JavaAlex GView Answer on Stackoverflow