Class Joiner

java.lang.Object
com.google.mu.util.stream.Joiner
All Implemented Interfaces:
Collector<Object,StringJoiner,String>

public final class Joiner extends Object implements Collector<Object,StringJoiner,String>
A joiner (and Collector) that joins strings.

When used to join a pair of objects (for example in a BiStream), it can be used for BiFunction:


   BiStream.zip(userIds, names)
       .mapToObj(Joiner.on('=')::join)  // (id, name) -> id + "=" + name
       ....;
 

Alternatively, it can be used as a Collector. For example, names.collect(Joiner.on(',')) is equivalent to names.collect(Collectors.joining(",")). Except that JDK joining() requires the inputs to be strings; while Joiner can join any input, e.g. numbers.

You can also chain between(char, char) to further enclose the joined result between a pair of strings. The following code joins a list of ids and their corresponding names in the format of "[id1=name1, id2=name2, id3=name3, ...]" by first joining each pair with '=' and then joining the "id=name" entries with ',', finally enclosing them between '[' and ']':


   BiStream.zip(userIds, names)
       .mapToObj(Joiner.on('=')::join)
       .collect(Joiner.on(", ").between('[', ']'));
 
Which reads clearer than using JDK Collectors.joining():

   BiStream.zip(userIds, names)
       .mapToObj(id, name) -> id + "=" + name)
       .collect(Collectors.joining(", ", "[", "]"));
 

If you need to skip nulls and/or empty strings while joining, use collect(Joiner.on(...).skipNulls()) or collect(Joiner.on(...).skipEmpties()) respectively.

Unlike Guava com.google.common.base.Joiner, nulls don't cause NullPointerException, instead, they are stringified using String.valueOf(java.lang.Object).

Since:
5.6