Google Guava in Java to join String with Joiner

Tags: Google Guava String

Java Code Examples for using com.google.common.base.Joiner class

Example for using Joiner that skip joining null values

package simplesolution.dev;

import com.google.common.base.Joiner;

public class GuavaJoinerExample1 {

    public static void main(String... args) {
        final Joiner joiner = Joiner.on(" and ").skipNulls();
        String result = joiner.join("Java", "Python", null, "Go");
        System.out.println(result);
    }
}
Output

Java and Python and Go

Example for using Joiner to join objects

package simplesolution.dev;

import com.google.common.base.Joiner;

public class GuavaJoinerExample2 {

    public static void main(String... args) {
        Joiner joiner = Joiner.on(',');
        Object[] items = new Object[]{1, 2, 3, 4, 5, 6, 7};
        String result = joiner.join(items);
        System.out.println(result);
    }
}
Output

1,2,3,4,5,6,7

Example for using Joiner to substitute value for any null object

package simplesolution.dev;

import com.google.common.base.Joiner;

public class GuavaJoinerExample3 {

    public static void main(String... args) {
        String result = Joiner.on(';')
                                .useForNull("NULLVALUE")
                                .join("Python", null, "Java", "Go");
        System.out.println(result);
    }
}
Output

Python;NULLVALUE;Java;Go

Happy Coding 😊