ava 10 introduced a new method called Collectors.toUnmodifiableList()
that returns an unmodifiable List which is a view over the original List. In this article, we will explore the toUnmodifiableList()
method and how it can be used in Java programming.
Introduction to Collectors.toUnmodifiableList() Method
The Collectors.toUnmodifiableList()
method returns an unmodifiable List that is a view over the original List. It is similar to the Collectors.toList()
method, but the returned List is unmodifiable, which means that any attempt to modify it will result in an UnsupportedOperationException
.
Syntax
public static <T> Collector<T, ?, List<T>> toUnmodifiableList()
Example
Let’s consider an example where we have a List of integers and we want to filter out the even numbers and return an unmodifiable List of odd numbers. We can use the toUnmodifiableList()
method to achieve this as follows:
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class UnmodifiableListExample {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
List<Integer> oddNumbers = numbers.stream()
.filter(n -> n % 2 != 0)
.collect(Collectors.toUnmodifiableList());
System.out.println("Original List: " + numbers);
System.out.println("Unmodifiable List of odd numbers: " + oddNumbers);
// Attempt to modify the unmodifiable List
try {
oddNumbers.add(11);
} catch (UnsupportedOperationException ex) {
System.out.println("Cannot modify unmodifiable List: " + ex.getMessage());
}
}
}
In the example above, we first created a List of integers and then used the stream()
method to filter out the even numbers and create a new List of odd numbers. We then used the toUnmodifiableList()
method to convert the new List into an unmodifiable List. Finally, we printed both the original List and the unmodifiable List to the console.
When we try to modify the unmodifiable List by adding a new element to it, we get an UnsupportedOperationException
as expected.
Benefits of Collectors.toUnmodifiableList() Method
The toUnmodifiableList()
method provides an easy and efficient way to create unmodifiable Lists in Java. It is especially useful when we want to create a List that cannot be modified by other parts of the code, as this can help us ensure data integrity and avoid bugs that might arise from accidental modifications to the List.
Conclusion
In this article, we explored the Collectors.toUnmodifiableList()
method of Java and how it can be used to create unmodifiable Lists. We also looked at an example that demonstrated the usage of the method and the benefits it provides. By using this method, we can ensure data integrity and avoid bugs that may arise from accidental modifications to our Lists.