The simplest way to comma-delimit a list?
Java 8 and later
Using StringJoiner
class, and forEach
method :
StringJoiner joiner = new StringJoiner(",");list.forEach(item -> joiner.add(item.toString());return joiner.toString();
Using Stream
, and Collectors
:
return list.stream(). map(Object::toString). collect(Collectors.joining(",")).toString();
Java 7 and earlier
See also #285523
String delim = "";for (Item i : list) { sb.append(delim).append(i); delim = ",";}
Java 8 provides several new ways to do this:
- The
join
method onString
. - A
joining
collector for streams from theCollectors
class. - The
StringJoiner
class.
Example:
// Util method for strings and other char sequencesList<String> strs = Arrays.asList("1", "2", "3");String listStr1 = String.join(",", strs);// For any type using streams and collectorsList<Object> objs = Arrays.asList(1, 2, 3);String listStr2 = objs.stream() .map(Object::toString) .collect(joining(",", "[", "]"));// Using the new StringJoiner classStringJoiner joiner = new StringJoiner(", ", "[", "]");joiner.setEmptyValue("<empty>");for (Integer i : objs) { joiner.add(i.toString());}String listStr3 = joiner.toString();
The approach using streams assumes import static java.util.stream.Collectors.joining;
.