Guava Tips: Splitter and Joiner

Splitting strings, or building them from collections of objects, is a common task in any program. As usual, Guava has you covered with its two classes Splitter and Joiner.

Splitter Link to heading

The Splitter class can split a String according to

  • a character;
  • a fixed string;
  • a regular expression;
  • a CharMatcher

or even in pieces of the same fixed length. Creating a Splitter is quite simple:

Splitter onSpace = Splitter.on(' ');
Iterable<String> parts = onSpace.split("a bc def");

Splitter otherSplitter = Splitter.on(Patter.compile("\\s+))
                                 .trimResults()
                                 .omitEmptyStrings();

Splitters are immutable and thread-safe, which means that they can safely be stored in a static final variable. The default behavior is to return an Iterable<String>; however a method splitToList is provided if you want to build a List<String>.

Joiner Link to heading

Joiner does the opposite of Splitter: it creates a String by joining objects, using their toString method. For instance:

String s = Joiner.on(", ").join("a", "b", "c");
assertEquals("a, b, c", s);

Joiner provides a lot of useful variants its two main methods:

  • join can take an Iterable, an array, or an Iterator;
  • appendTo can be used to add the generated String to a StringBuilder, a Writer or other Appendable; again, it can take Iterable, Iterator or arrays.

Finally, there’s a way (calling skipNulls) to create a Joiner which will skip null objects in its arguments, and another (using useForNull) to replace them with a default string.

Similarly to Splitter, Joiner instances are thread-safe and immutable.