Joining a List<String> in Java with commas and "and" Joining a List<String> in Java with commas and "and" java java

Joining a List<String> in Java with commas and "and"


In Java 8 you can use String.join() like following:

Collection<String> elements = ....;String result = String.join(", ", elements);


With Java 8, you can use streams with joiners.

Collection<String> strings;...String commaDelimited = strings.stream().collect(Collectors.joining(","));// use strings.parallelStream() instead, if you think//   there are gains to be had by doing fork/join


What about join from:org.apache.commons.lang.StringUtils

Example:

StringUtils.join(new String[] { "one", "two", "three" }, ", "); // one, two, three

To have "and" or ", and" you can simple replace the last comma.