Collectors.toUnmodifiableList() in Java

Introduction

Java 10 introduced the Collectors.toUnmodifiableList() method as part of the Java Collections Framework. This method is used in conjunction with the Java Stream API to collect elements into an unmodifiable list. Once created, the resulting list cannot be modified, making it a convenient way to create immutable lists directly from streams.

Key Points:

  • Immutable List: Collectors.toUnmodifiableList() creates a list that cannot be modified.
  • Stream API: Used with streams to collect elements into an unmodifiable list.
  • Read-Only: Any attempt to modify the resulting list will throw an UnsupportedOperationException.
  • Null Safety: If the stream contains null elements, the collector will throw a NullPointerException.

How to Use Collectors.toUnmodifiableList()

The Collectors.toUnmodifiableList() method is used as a terminal operation in a stream pipeline to collect elements into an unmodifiable list.

Syntax:

List<Type> unmodifiableList = stream.collect(Collectors.toUnmodifiableList()); 
  • stream: A stream of elements to be collected.
  • unmodifiableList: The resulting read-only list.

Example of Using Collectors.toUnmodifiableList()

Basic Example

Here’s a simple example demonstrating the use of Collectors.toUnmodifiableList() with a list of Indian city names:

import java.util.List; import java.util.stream.Collectors; import java.util.stream.Stream; public class UnmodifiableListExample { public static void main(String[] args) { // Create a stream of city names Stream<String> cityStream = Stream.of("Mumbai", "Delhi", "Bengaluru", "Chennai"); // Collect the stream elements into an unmodifiable list List<String> cityList = cityStream.collect(Collectors.toUnmodifiableList()); System.out.println("Unmodifiable City List: " + cityList); // Attempt to modify the unmodifiable list try { cityList.add("Hyderabad"); // This will throw UnsupportedOperationException } catch (UnsupportedOperationException e) { System.out.println("Cannot modify cityList: " + e.getMessage()); } } } 

Output:

Unmodifiable City List: [Mumbai, Delhi, Bengaluru, Chennai] Cannot modify cityList: null 

Explanation:

  • Immutable List: The Collectors.toUnmodifiableList() method creates a list that cannot be modified, ensuring the list’s content is protected.
  • Error on Modification: Any attempt to modify the resulting list, such as adding or removing elements, will result in an UnsupportedOperationException.

Real-World Example

Using Collectors.toUnmodifiableList() is beneficial when you want to create a list from a stream and ensure that the list remains unchanged.

Example with Fruit Prices:

import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; public class FruitPriceExample { public static void main(String[] args) { // Create a map of fruit names and their prices Map<String, Integer> fruitPrices = Map.of( "Mango", 50, "Banana", 20, "Apple", 70, "Orange", 60 ); // Create a stream of fruits priced above 30 Stream<String> expensiveFruitsStream = fruitPrices.entrySet().stream() .filter(entry -> entry.getValue() > 30) .map(Map.Entry::getKey); // Collect the stream elements into an unmodifiable list List<String> expensiveFruitsList = expensiveFruitsStream.collect(Collectors.toUnmodifiableList()); System.out.println("Expensive Fruits List: " + expensiveFruitsList); // Attempt to modify the unmodifiable list try { expensiveFruitsList.add("Grapes"); // This will throw UnsupportedOperationException } catch (UnsupportedOperationException e) { System.out.println("Cannot modify expensiveFruitsList: " + e.getMessage()); } } } 

Output:

Expensive Fruits List: [Mango, Apple, Orange] Cannot modify expensiveFruitsList: null 

Explanation:

  • Stream Processing: The example filters fruits priced above 30 and collects the results into an unmodifiable list using Collectors.toUnmodifiableList().
  • Immutable List: The resulting list is immutable, ensuring that the list remains unchanged.
  • Error on Modification: Any attempt to add an element to the list results in an UnsupportedOperationException.

Conclusion

The Collectors.toUnmodifiableList() method in Java 10 provides a simple way to create immutable lists from streams. This feature is particularly useful when you want to ensure that a list created from a stream remains read-only, enhancing the safety and reliability of your code.

Summary:

  • Immutable List: Creates a list that cannot be modified.
  • Stream API: Collects elements from streams into an unmodifiable list.
  • Read-Only: The resulting list is read-only, preventing any modifications.
  • Null Safety: The collector will throw a NullPointerException if the stream contains null elements.

By using Collectors.toUnmodifiableList(), you can create safe, immutable lists in your Java applications, making your code more robust and reliable.

Leave a Comment

Scroll to Top