Splitting and joining Strings with Google Guava

Google Guava is a Java utility library from Google. Guava contains many useful features and methods that make Java programming simpler and easier.

One recurring thing that Java developers need to do over and over again is joining and splitting strings. Guava contains useful tools for both of these operations and next we’re going to look at them:

String splitting

import com.google.common.base.Splitter;

public class GuavaSplitter {

    private static final String SEQUENCE = "one, two, three,,four";

    public static void main(String[] args) {

        // Simple example
        Iterable<String> simple = Splitter.on(',').split(SEQUENCE);

        System.out.println("Simple example:");
        for(String part : simple) {
            System.out.println(part);
        }

        // Advanced example
        Splitter splitter = Splitter.on(',').trimResults().omitEmptyStrings();
        Iterable<String> advanced = splitter.split(SEQUENCE);

        System.out.println("\nAdvanced example:");
        for(String part : advanced) {
            System.out.println(part);
        }
    }

}

Output

Simple example:
one
 two
 three

four

Advanced example:
one
two
three
four

The simple example shows you the most common way to use the splitter. The split point is set with the on() method and the string is given to the split() method.

But as you can see in the output, the parts are not trimmed and empty parts are not ignored which means that the parts will contain the leading (and/or following) white spaces and there may be parts that are empty.

The advanced example takes care of the trimming and shows how to ignore empty parts. You’ll need to initialize the Splitter with trimResults() and omitEmptyString() methods and you’re good to go.

String joining

import com.google.common.base.Joiner;

public class GuavaJoiner {

    public static void main(String[] args) {

        // Simple example
        String simple = Joiner.on(", ").join("one", "two", "three", "four");

        System.out.println("Simple Example:");
        System.out.println(simple);

        //  Advanced example
        Joiner joiner = Joiner.on(", ").skipNulls();
        String advanced = joiner.join("one", "two", "three", null, "four");

        System.out.println("\nAdvanced Example:");
        System.out.println(advanced);
    }

}

Output

Simple Example:
one, two, three, four

Advanced Example:
one, two, three, four

The simple join example shows how the joiner works. You set the joining string with on() method and the parts are given with join().

The advanced example shows how to handle null in the join list. If skipNulls() is not called, like in the simple example, the join() method will throw a NullPointerException.

Further reading

Comments

comments powered by Disqus