Open In App

Collectors toSet() in Java with Examples

Collectors toSet() returns a Collector that accumulates the input elements into a new Set. There are no guarantees on the type, mutability, serializability, or thread-safety of the Set returned. This is an unordered Collector i.e, the collection operation does not commit to preserving the encounter order of input elements.

Syntax:



public static <T> Collector<T, ?, Set<T>> toSet()

where:

Return Value: A Collector which collects all the input elements into a Set.



Below are the examples to illustrate toSet() method:

Example 1:




// Java code to show the implementation of
// Collectors toSet() function
  
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
  
class GFG {
  
    // Driver code
    public static void main(String[] args)
    {
        // creating a Stream of strings
        Stream<String> s = Stream.of("Geeks",
                                     "for",
                                     "GeeksforGeeks",
                                     "Geeks Classes");
  
        // using Collectors toSet() function
        Set<String> mySet = s.collect(Collectors.toSet());
  
        // printing the elements
        System.out.println(mySet);
    }
}

Output:
[Geeks Classes, GeeksforGeeks, Geeks, for]

Example 2:




// Java code to show the implementation of
// Collectors toSet() function
  
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
  
class GFG {
  
    // Driver code
    public static void main(String[] args)
    {
  
        // creating a Stream of strings
        Stream<String> s = Stream.of("1", "2", "3", "4");
  
        // using Collectors toSet() function
        Set<String> mySet = s.collect(Collectors.toSet());
  
        // printing the elements
        System.out.println(mySet);
    }
}

Output:
[1, 2, 3, 4]

Article Tags :