How do I use String.join() method in Java?

The String.join() method in Java is a static method added in Java 8 to the java.lang.String class. The String.join() is a static utility method used to concatenate multiple strings, arrays or collections (like lists and sets) of strings. This method makes it easier to join multiple strings with a specific delimiter. A delimiter is a sequence of characters used to separate strings.

This method returns a new String composed of copies of the CharSequence elements joined together with a copy of the specified delimiter. This method saves us from writing boilerplate loop code just for concatenating strings with a delimiter.

Here is an example of how you can use it:

package org.kodejava.lang;

import java.util.Arrays;
import java.util.List;

public class StringJoinList {
    public static void main(String[] args) {
        List<String> list = Arrays.asList("Java", "is", "cool");
        String result = String.join(" ", list);
        System.out.println(result);
    }
}

Output:

Java is cool

In this example, String.join() takes two parameters:

  1. A delimiter that is a CharSequence (like a String) that is placed between each joined String.
  2. An Iterable object like a List or a Set, over which the method iterates and joins all elements into a single String.

You can also use String.join() with an array of elements:

package org.kodejava.lang;

public class StringJoinArray {
    public static void main(String[] args) {
        String[] array = new String[]{"Java", "is", "cool"};
        String result = String.join(" ", array);
        System.out.println(result);
    }
}

Output:

Java is cool

In this case, String.join() still takes a delimiter as the first argument, but the second argument is an Array of elements to be joined.

How do I use Collectors.joining() method?

The Collectors.joining() method is a handy utility in the java.util.stream.Collectors class that provides a Collector which concatenates input elements from a stream into a String.

Here are three versions of Collectors.joining():

  • joining(): Concatenates the input elements, separated by the empty string.
  • joining(CharSequence delimiter): Concatenates the input elements, separated by the specified delimiter.
  • joining(CharSequence delimiter, CharSequence prefix, CharSequence suffix): Concatenates the input elements, separated by the delimiter, with the specified prefix and suffix.

Let’s see an example of each:

package org.kodejava.stream;

import java.util.stream.Collectors;
import java.util.stream.Stream;

public class CollectorsJoining {
    public static void main(String[] args) {
        // Using joining()
        String joined1 = Stream.of("Hello", "world")
                .collect(Collectors.joining());
        System.out.println(joined1);

        // Using joining(CharSequence delimiter)
        String joined2 = Stream.of("Hello", "world")
                .collect(Collectors.joining(" "));
        System.out.println(joined2);

        // Using joining(CharSequence delimiter, CharSequence prefix,
        // CharSequence suffix)
        String joined3 = Stream.of("Hello", "world")
                .collect(Collectors.joining(", ", "[", "]"));
        System.out.println(joined3);
    }
}

Output:

Helloworld
Hello world
[Hello, world]

In these examples, we use Stream.of() to create a stream of strings, and Collectors.joining() to concatenate them together, with or without delimiters, prefix, and suffix as needed.

Now, let’s consider we have a Person class and a list of Person objects. We want to join the names of all persons. Here is how to do that:

package org.kodejava.stream;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

class Person {
    private final String name;

    public Person(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }
}

public class CollectorsJoiningObjectProperty {
    public static void main(String[] args) {
        List<Person> people = Arrays.asList(
                new Person("John"),
                new Person("Rosa"),
                new Person("Doe")
        );

        String names = people.stream()
                .map(Person::getName)
                .collect(Collectors.joining(", "));

        System.out.println(names);
    }
}

Output:

John, Rosa, Doe

In the above example, we start with a List of Person objects. We create a stream from the list, then use the map() function to transform each Person into a String (their name). The collect() method is then used with Collectors.joining(), which joins all the names together into one String, separated by commas.