Collectors.toUnmodifiableSet() in Java

Introduction

Java 10 introduced the Collectors.toUnmodifiableSet() method, which is used to collect elements from a stream into an unmodifiable set. This method is part of the Java Stream API and allows you to create read-only sets directly from streams, ensuring that the resulting set cannot be modified.

Key Points:

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

How to Use Collectors.toUnmodifiableSet()

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

Syntax:

Set<Type> unmodifiableSet = stream.collect(Collectors.toUnmodifiableSet());
  • stream: A stream of elements to be collected.
  • unmodifiableSet: The resulting read-only set.

Example of Using Collectors.toUnmodifiableSet()

Basic Example

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

import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class UnmodifiableSetExample {
    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 set
        Set<String> citySet = cityStream.collect(Collectors.toUnmodifiableSet());

        System.out.println("Unmodifiable City Set: " + citySet);

        // Attempt to modify the unmodifiable set
        try {
            citySet.add("Hyderabad");  // This will throw UnsupportedOperationException
        } catch (UnsupportedOperationException e) {
            System.out.println("Cannot modify citySet: " + e.getMessage());
        }
    }
}

Output:

Unmodifiable City Set: [Mumbai, Delhi, Bengaluru, Chennai]
Cannot modify citySet: null

Explanation:

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

Null Safety

The Collectors.toUnmodifiableSet() method does not allow null elements in the stream. If the stream contains null, a NullPointerException is thrown.

Example:

import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class NullSafetyExample {
    public static void main(String[] args) {
        // Create a stream with a null element
        Stream<String> cityStream = Stream.of("Mumbai", null, "Chennai");

        try {
            // Attempt to collect the stream into an unmodifiable set
            Set<String> citySet = cityStream.collect(Collectors.toUnmodifiableSet());
        } catch (NullPointerException e) {
            System.out.println("Stream contains null elements: " + e.getMessage());
        }
    }
}

Output:

Stream contains null elements: null

Explanation:

  • No Null Elements: The Collectors.toUnmodifiableSet() method ensures that the resulting set does not contain null elements. If the stream contains null, a NullPointerException is thrown.

Real-World Example

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

Example with Fruit Names:

import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class FruitExample {
    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 set
        Set<String> expensiveFruitsSet = expensiveFruitsStream.collect(Collectors.toUnmodifiableSet());

        System.out.println("Expensive Fruits Set: " + expensiveFruitsSet);

        // Attempt to modify the unmodifiable set
        try {
            expensiveFruitsSet.add("Grapes");  // This will throw UnsupportedOperationException
        } catch (UnsupportedOperationException e) {
            System.out.println("Cannot modify expensiveFruitsSet: " + e.getMessage());
        }
    }
}

Output:

Expensive Fruits Set: [Mango, Apple, Orange]
Cannot modify expensiveFruitsSet: null

Explanation:

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

Conclusion

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

Summary:

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

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

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top