What is Collectors.toUnmodifiableSet() in Java?

What is the collectors class?

Collectors is a utility class that provides various implementations of reduction operations, such as grouping elements, adding them to different collections, summarizing them according to various criteria, etc. The different functionalities in the Collectors class are usually used as the final operation on streams.

The toUnmodifiableSet() method

toUnmodifiableSet() is a static method of the Collectors class that collects or accumulates all the elements to a new unmodifiable set. This method returns a Collector that disallows null values, and raises a NullPointerException if supplied with null values. If any duplicate elements are present, this method retains an arbitrary instance of the duplicates. This method was introduced in Java 10.

The toUnmodifiableSet method is defined in the Collectors class which is defined in the java.util.stream package. To import the Collectors class, we use the following import statement.

import java.util.stream.Collectors;

Syntax


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

Parameters

The method has no parameters.

Return value

This method returns a collector that collects all the input elements into an unmodifiable set in the encounter order.

Code

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class main {
public static void main(String[] args) {
List<String> stringList = Arrays.asList("educative", "io", "edpresso", "educative", "io", "edpresso");
System.out.println("Stream before modification - " + stringList);
Stream<String> stringStream = stringList.stream();
Set<String> uppercaseSet = stringStream.map(String::toUpperCase).collect(Collectors.toUnmodifiableSet());
System.out.println("Resulting set after modification - " + uppercaseSet);
uppercaseSet.add("test");
}
}

Explanation

  • Lines 1 to 4: We import the relevant packages.
  • Line 10: We define a list of strings called stringList.
  • Line 12: We print the stringList.
  • Line 14: We create a stream out of the stringList.
  • Line 16: We convert the elements of the stream to uppercase using the map method. We then collect the resulting elements to a new unmodifiable set, using the toUnmodifiableSet method.
  • Line 18: We print the new set of uppercase elements.
  • Line 20: We try to add an element to the returned unmodifiable set, which throws an exception.

Free Resources