Java Joining List of Strings

Today w’ll see different ways of joining a List of Strings

Let’s say we have the following list

List list = new ArrayList<>();
list.add("Bob");
list.add("Ann");
list.add("Sem");

1. Java 8 Stream API

String joined = list.stream().collect(Collectors.joining(", "));

Output: Bob, Ann, Sem

2. Java 8 String.join()

joined = String.join(", ", list);

Output: Bob, Ann, Sem
//null will not be skipped
String joined = String.join(", ", "Bob", "Ann", null, "Sem");
[addToAppearHere]

3. Apache Commons StringUtils.join()

String joined = StringUtils.join(list, ", ");

Output: Bob, Ann, Sem
//null will be skipped
String joined = StringUtils.join("Bob ", "Ann ", null, "Sem");

Output: Bob Ann Sem

4. Guava Joiner.join()

String joined = Joiner.on(", ").join(list);

Output: Bob, Ann, Sem
//if null not skipped, will trow exception
joined = Joiner.on(", ").skipNulls().join("Bob", "", "Ann", null, "Sem");

Output: Bob, , Ann, Sem