Veit's Blog

Hej! đź‘‹ Welcome to my curated space of insights on software development and the tapestry of life.

Guava Joiner Class

2016-04-01

Although I’m a long time user of Google Guava I discovered the class Joiner just a few days ago. Eventually everybody who’s familiar with Googles Apache Commons alternative have heard about it, but I like to show the usage for those who didn’t know yet.

Given the following list:

List<String> nameList = Lists.newArrayList("Solo", "Kenobi", "Skywalker", "Yoda");
String delimiter = ",";

You usually would do the following to join the items in one string:

StringBuilder result = new StringBuilder();

for(String name: nameList){
  if(name != null)
    result.append(name).append(delimiter);
}
result.setLength(result.length() - delimiter.length());

return result.toString();
return Joiner.on(delimiter).join(nameList);

There are a lot more overloaded variants of the method on. Also have a look at the class Splitter.

BTW: With streams it’s simple too:

return nameList.stream().collect(Collectors.joining(delimiter));