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.

Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.