Which Java 10 feature allows you to collect elements into an unmodifiable list using Collectors?

Java MCQ: Which Java 10 feature allows you to collect elements into an unmodifiable list using Collectors?

a) Collectors.toUnmodifiableSet()
b) Collectors.toUnmodifiableMap()
c) Collectors.toUnmodifiableList()
d) Collectors.toImmutableList()

Answer:

c) Collectors.toUnmodifiableList()

Explanation:

The Collectors.toUnmodifiableList() method, introduced in Java 10, allows you to collect elements into an unmodifiable list. This method is part of the java.util.stream.Collectors class and is used in conjunction with the Stream API to create lists that cannot be modified after they are created.

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

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

public class ToUnmodifiableListExample {
    public static void main(String[] args) {
        List<String> list = Stream.of("Apple", "Banana", "Cherry")
                                      .collect(Collectors.toUnmodifiableList());

        System.out.println(list);

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

In this example, Collectors.toUnmodifiableList() is used to collect elements from a stream into an unmodifiable list. Any attempt to modify the resulting list (e.g., adding or removing elements) will throw an UnsupportedOperationException.

The Collectors.toUnmodifiableList() method is useful when you need a read-only list 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