Introduction to Google Guava's Joiner class
The Joiner
class performs the complementary function of the Splitter
class. The Joiner
class will join an Iterable
, an array, or a variable argument list using a given separator in between them.
Starting with the basics
The basic usage of the Joiner
uses the on
function and then by calling join
with an array or Iterator
object. To demonstrate this, let us use a Set
of names to create a comma separated list.
Dealing with nulls
Like the Splitter
, the Joiner
comes with a couple of utilities for dealing with null
in the input. The first is the skipNulls
function that will return a Joiner
which will automatically skip over any nulls it encounters when iterating over the elements. The second is the useForNull
function which will use the parameter it was given in place of nulls. Here are examples of using each one:
If you use both the skipNulls
and useForNull
on the same joiner, it will throw an UnsupportedOperationException
.
Using the Joiner
class to build up a StringBuilder
In addition to joining a String
all at the same time, you can build it up instead using a StringBuilder
. The appendTo
function of the Joiner
takes the same arguments as the join
function: an Iterable, array, or argument list an will work for both StringBuilders
and any Appendable
object. One caveat of this function is that it will only add the separator between elements within each function call. Below is an example of using it with a StringBuilder
.
As you can see, the commas were only added in between elements in the same appendTo
call which is why johndanmatt
was not separated.
Using the MapJoiner (new in Guava 10.0)
A good example of using a MapJoiner
is to create a query string out of a Map
of query parameters. Let us use the following map:
{"param": "v", "p2": "v2", "q": "java"}
And the code:
The MapJoiner
does not have utilities for trimming and cleaning up the strings, so that will have to be done while building the Map
. You can read the full documentation on the Joiner
class here.