Java 8 StringJoiner
At the release of Java 8 the most attention went to the Lamda’s, the new Date API and the Nashorn Javascript engine. In the shade of these, there are smaller but also interesting changes. Amongst them is the introduction of a StringJoiner. The StringJoiner is a utility to delimit a list of characters or strings. You may recognize the code below:
String getString(List<String> items)
StringBuilder sb = new StringBuilder();
for(String item : items) {
if(sb.length != 0) {
sb.append(",");
}
sb.append(item);
}
return sb.toString();
}
This can be replaced by these lines in Java 8:
String getString(List<String> items) {
StringJoiner stringJoiner = new StringJoiner(", ");
for(String item : items) {
stringJoiner.add(item);
}
return stringJoiner.toString();
}
If you already know how to use streams, the following code will reduce some obsolete lines.
String getString(List<String> items) {
StringJoiner stringJoiner = new StringJoiner(", ");
items.stream().forEach(stringJoiner::add);
return stringJoiner.toString();
}
Another valuable addition is to set a prefix and a suffix. They can be set as second and third parameter in the StringJoiner constructor. For example:
String getString(List<String> items) {
StringJoiner stringJoiner = new StringJoiner(", ", "<<", ">>");
items.stream().forEach(stringJoiner::add);
return stringJoiner.toString();
}
This code can return for example:
<<One, Two, Tree, Four>>
Another way to compose a new String from an iterable is using the Join method on the String class. The Join method supports a seperator, but no prefix and suffix. You can use it as follows:
String result = String.join(", ", "One", "Two", "Three");
The result will be:
One, Two, Three