Java Collectors toUnmodifiableSet() Method

The toUnmodifiableSet() method in Java, part of the java.util.stream.Collectors class, is used to collect elements of a stream into an unmodifiable Set. This method is useful when you need to create a set that should not be modified after its creation.

Table of Contents

  1. Introduction
  2. toUnmodifiableSet() Method Syntax
  3. Understanding toUnmodifiableSet()
  4. Examples
    • Basic Usage
    • Using toUnmodifiableSet() with Custom Objects
  5. Real-World Use Case
  6. Conclusion

Introduction

The toUnmodifiableSet() method returns a Collector that accumulates the input elements into an unmodifiable Set. This method is particularly useful for creating read-only sets to ensure that the collected elements are unique and cannot be modified after creation.

toUnmodifiableSet() Method Syntax

The syntax for the toUnmodifiableSet() method is as follows:

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

Parameters:

  • This method does not take any parameters.

Returns:

  • A Collector that collects the input elements into an unmodifiable Set.

Throws:

  • This method does not throw any exceptions.

Understanding toUnmodifiableSet()

The toUnmodifiableSet() method allows you to collect the elements of a stream into an unmodifiable Set. The resulting set is immutable, meaning that attempts to modify it will result in an UnsupportedOperationException.

Examples

Basic Usage

To demonstrate the basic usage of toUnmodifiableSet(), we will create a stream of integers and collect them into an unmodifiable set.

Example

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class ToUnmodifiableSetExample {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 1, 2);

        // Collect the numbers into an unmodifiable set
        Set<Integer> unmodifiableSet = numbers.stream()
                                              .collect(Collectors.toUnmodifiableSet());

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

        // Attempting to modify the set will result in an UnsupportedOperationException
        // unmodifiableSet.add(6); // Uncommenting this line will throw an exception
    }
}

Output:

Unmodifiable Set: [1, 2, 3, 4, 5]

Using toUnmodifiableSet() with Custom Objects

This example shows how to use toUnmodifiableSet() with a stream of custom objects to collect them into an unmodifiable set.

Example

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class ToUnmodifiableSetCustomObjectExample {
    static class Product {
        String name;
        double price;

        Product(String name, double price) {
            this.name = name;
            this.price = price;
        }

        @Override
        public String toString() {
            return name + " ($" + price + ")";
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;

            Product product = (Product) o;

            return Double.compare(product.price, price) == 0 && name.equals(product.name);
        }

        @Override
        public int hashCode() {
            int result;
            long temp;
            result = name.hashCode();
            temp = Double.doubleToLongBits(price);
            result = 31 * result + (int) (temp ^ (temp >>> 32));
            return result;
        }
    }

    public static void main(String[] args) {
        List<Product> products = Arrays.asList(
            new Product("Product A", 10.0),
            new Product("Product B", 20.5),
            new Product("Product C", 15.8),
            new Product("Product A", 10.0)
        );

        // Collect the products into an unmodifiable set
        Set<Product> unmodifiableProductSet = products.stream()
                                                      .collect(Collectors.toUnmodifiableSet());

        System.out.println("Unmodifiable Product Set: " + unmodifiableProductSet);

        // Attempting to modify the set will result in an UnsupportedOperationException
        // unmodifiableProductSet.add(new Product("Product D", 30.0)); // Uncommenting this line will throw an exception
    }
}

Output:

Unmodifiable Product Set: [Product B ($20.5), Product A ($10.0), Product C ($15.8)]

Real-World Use Case

Collecting Unique Employee Names

In real-world applications, the toUnmodifiableSet() method can be used to collect the unique names of employees into a set.

Example

import java.util.Arrays;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class EmployeeNameSetExample {
    static class Employee {
        String name;
        int age;

        Employee(String name, int age) {
            this.name = name;
            this.age = age;
        }

        String getName() {
            return name;
        }
    }

    public static void main(String[] args) {
        List<Employee> employees = Arrays.asList(
            new Employee("Alice", 30),
            new Employee("Bob", 25),
            new Employee("Charlie", 35),
            new Employee("Alice", 28)
        );

        // Collect the unique employee names into an unmodifiable set
        Set<String> nameSet = employees.stream()
                                       .map(Employee::getName)
                                       .collect(Collectors.toUnmodifiableSet());

        System.out.println("Unmodifiable Name Set: " + nameSet);

        // Attempting to modify the set will result in an UnsupportedOperationException
        // nameSet.add("David"); // Uncommenting this line will throw an exception
    }
}

Output:

Unmodifiable Name Set: [Alice, Bob, Charlie]

Conclusion

The Collectors.toUnmodifiableSet() method is used to collect the elements of a stream into an unmodifiable Set. This method is particularly useful for creating read-only sets to ensure that the collected elements are unique and cannot be modified after creation. By understanding and using this method, you can efficiently manage immutable collection operations in your Java applications.

Comments