What is Collectors.toUnmodifiableList() in Java?

What is the collectors class?

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

The toUnmodifiableList() method

toUnmodifiableList() is a static method of the Collectors used to collect/accumulate all the elements to a new unmodifiable list. The method returns a Collector that collects all the input elements into an unmodifiable list, and which disallows null values, raising a NullPointerException if it’s supplied with null values. This method was introduced in Java 10.

The toUnmodifiableList method is defined in the Collectors class. The Collectors class is defined in the java.util.stream package. To import the Collectors class, check the following import statement.

import java.util.stream.Collectors;

Syntax

public static <T> Collector<T, ?, List<T>> toUnmodifiableList()

Parameters

The method has no parameters.

Return value

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

Code

import java.util.Arrays;
import java.util.List;
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");
System.out.println("Stream before modification - " + stringList);
Stream<String> stringStream = stringList.stream();
List<String> uppercaseList = stringStream.map(String::toUpperCase).collect(Collectors.toUnmodifiableList());
System.out.println("Resulting list after modification - " + uppercaseList);
uppercaseList.add("test");
}
}

Explanation

  • Lines 1-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 and collect the resulting elements to a new unmodifiable list using the toUnmodifiableList method.
  • Line 18: We print the new list of uppercase elements.
  • Line 20: We try to add an element to the returned unmodifiable list which throws an exception.

Free Resources