Join String list elements with a delimiter in one step
JavaJava 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
Java 8...
String joined = String.join("+", list);
Documentation: http://docs.oracle.com/javase/8/docs/api/java/lang/String.html#join-java.lang.CharSequence-java.lang.Iterable-
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.