Java Join Strings using Guava Joiner

Tags: Guava Joiner String

In this Java Guava tutorial we learn how to use the Guava library’s Joiner class to join the String values in Java programs.

Table of contents

  1. Add Guava dependency to Java project
  2. How to join String values in Java
  3. How to join String values contains null
  4. How to join a list of Strings in Java

Add Guava dependency to Java project

First step, adding the Guava dependency to the Java project.

If you use Gradle build project, add the following dependency to the build.gradle file.

implementation group: 'com.google.guava', name: 'guava', version: '31.1-jre'

If you use Maven build project, add the following dependency to the pom.xml file.

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>31.1-jre</version>
</dependency>

How to join String values in Java

To join multiple String values to a single String in Java with a given separator String we can use the Joiner class as the following example Java program.

JoinerExample1.java

import com.google.common.base.Joiner;

public class JoinerExample1 {
    public static void main(String... args) {
        // How to join String values in Java
        String separator = ", ";
        String result = Joiner.on(separator).join("FirstName", "LastName", "MobilePhone", "Email");

        System.out.println(result);
    }
}
The output as below.
FirstName, LastName, MobilePhone, Email

How to join String values contains null

With the skipNulls() method we can join String values include the null value as the following Java program.

JoinerExample2.java

import com.google.common.base.Joiner;

public class JoinerExample2 {
    public static void main(String... args) {
        // How to join String values contains null
        String separator = "; ";
        Joiner joiner = Joiner.on(separator).skipNulls();

        String result1 = joiner.join("Java", null, "Spring", "Kotlin");
        String result2 = joiner.join("Go", "Python", "Java", null, null);

        System.out.println(result1);
        System.out.println(result2);
    }
}
The output as below.
Java; Spring; Kotlin
Go; Python; Java

How to join a list of Strings in Java

In the following example Java program, we learn how to use the Guava’s Joiner class to join a List of String values.

JoinerExample3.java

import com.google.common.base.Joiner;
import com.google.common.collect.Lists;

import java.util.List;

public class JoinerExample3 {
    public static void main(String... args) {
        List<String> listOfStrings = Lists.newArrayList("Apple", "Orange", "Banana", "Mango");

        // How to join a List of Strings
        String result = Joiner.on(",").join(listOfStrings);

        System.out.println(result);
    }
}
The output as below.
Apple,Orange,Banana,Mango

Happy Coding 😊

Java Truncate ASCII String using Google Guava