What is the purpose of Collectors.toUnmodifiableSet() introduced in Java 10?

Java MCQ: What is the purpose of Collectors.toUnmodifiableSet() introduced in Java 10?

a) To create a mutable set from a stream
b) To create an unmodifiable set from a stream
c) To create a sorted set from a stream
d) To create a set that allows duplicate elements

Answer:

b) To create an unmodifiable set from a stream

Explanation:

The Collectors.toUnmodifiableSet() method, introduced in Java 10, is used to create an unmodifiable set from a stream. This method is part of the java.util.stream.Collectors class and allows developers to collect elements from a stream into a set that cannot be modified after it is created.

Here’s an example of using Collectors.toUnmodifiableSet():

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

public class ToUnmodifiableSetExample {
    public static void main(String[] args) {
        Set<String> set = Stream.of("Apple", "Banana", "Cherry")
                                    .collect(Collectors.toUnmodifiableSet());

        System.out.println(set);

        // This will throw UnsupportedOperationException because the set is unmodifiable
        // set.add("Mango");
    }
}

In this example, Collectors.toUnmodifiableSet() is used to collect elements from a stream into an unmodifiable set. Any attempt to modify the resulting set will throw an UnsupportedOperationException.

The Collectors.toUnmodifiableSet() method is useful when you need a read-only set that is guaranteed to remain unchanged, ensuring data integrity and preventing accidental modifications.

Reference links:

https://www.rameshfadatare.com/learn-java-programming/
https://www.javaguides.net/p/java-tutorial-learn-java-programming.html

Leave a Comment

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

Scroll to Top