Heyy, I’m Husain Sayyed, a software engineer passionate about exploring and sharing knowledge in Java, Spring Boot, and beyond. With several years of experience in development, I’ve decided to channel my learnings into blogging.
This is my first blog, and I’d love to hear your feedback to improve and make this journey engaging for all of us.
Today, I’ll be diving into the subtle but important differences between toList()
and Collectors.toList()
in Java — two methods that often puzzle developers when working with streams.
While these two methods might seem similar at first glance, their underlying implementations are quite different. Overlooking these differences can lead to subtle issues, such as unintended mutations or errors in your code.
The toList()
method is a new addition introduced in Java 16 while Collectors.toList()
is a part of the Java Stream API since Java 8.
The key difference between both of them is Mutability
. One method creates an Unmodifiable List while another create a Modifiable List.
Collectors.toList()
creates an Modifiable List, that you can use to add , update or remove elements.
List<String> list = Stream.of("A", "B", "C").collect(Collectors.toList());
list.add("D"); // Modifiable list
System.out.println(list); // prints [A, B, C, D]
toList()
creates an Unmodifiable List for you, see below :
List<String> list = Stream.of("A", "B", "C").toList();
System.out.println(list); // prints [A, B, C] so works fine
// but the moment you try to mutate the list, it will fail.
list.add("D"); // Throws Unsupported Error
I hope you never got to see this error, but If you see this later. Now you know what to do.
If you want to dive deep, You can see the internal implementation throws UnsupportedOperationException (uoe) in ImmutableCollections.java from java.util package.
So, when to use which methods, Use
ToList()
when immutability is required, or You know you will not mutate this list, or for thread safety or maintaining integrity.
Collectors.toList()
when you need a list that can be modified later.
_Understanding the subtle differences between toList()
and Collectors.toList()
can help you write more intentional and efficient Java code. While both have their place, the choice depends on your specific needs regarding mutability and Java version compatibility.
I hope you found this blog helpful and that it added some clarity to your understanding of toList()
and Collectors.toList()
in Java. Thanks for reading, and I’d love to hear your thoughts!_
Top comments (0)