How do I use Collectors.toSet() method?

The Collectors.toSet() method is a method from the java.util.stream.Collectors class that provides a Collector able to transform the elements of a stream into a Set.

Here’s an example of using the Collectors.toSet() method:

package org.kodejava.stream;

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

public class CollectorsToSet {
    public static void main(String[] args) {
        List<String> fruits = Arrays.asList("Apple", "Banana", "Orange", "Apple", "Banana", "Cherry");

        Set<String> uniqueFruits = fruits.stream()
                .collect(Collectors.toSet());

        System.out.println(uniqueFruits);
    }
}

Output:

[Apple, Cherry, Orange, Banana]

In this example, we have a List<String> of fruits, which contains some duplicate elements. When we stream the list and collect it into a Set using Collectors.toSet(), the result is a Set<String> that only includes the unique fruit names, as a Set doesn’t allow duplicate values.

Remember, like collect other terminal operation, it triggers the processing of the data and will return a collection or other specificity defined type. In case of Collectors.toSet(), the result is a Set.

Wayan

Leave a Reply

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