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.
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;
public static <T> Collector<T, ?, Set<T>> toUnmodifiableSet()
The method has no parameters.
This method returns a collector
that collects all the input elements into an unmodifiable set in the encounter order.
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");}}
stringList
.stringList
.stringList
.map
method. We then collect the resulting elements to a new unmodifiable set, using the toUnmodifiableSet
method.