Junior — Middle
What is the difference between the toList() method and the collect(Collectors.toList()) method in Java's Stream API?
sobes.tech AI
Answer from AI
In Java Stream API, the method collect(Collectors.toList()) is the standard way to gather stream elements into a list (List). It returns a new list containing all the stream elements.
The toList() method appeared in Java 16 as a shorter and more convenient way to collect elements into a list. It also returns a list, but with some differences:
Collectors.toList()does not guarantee a specific list implementation and may return, for example, anArrayList.Stream.toList()returns an immutable list that cannot be modified (e.g., adding or removing elements).
Example:
List<String> list1 = stream.collect(Collectors.toList()); // mutable list
List<String> list2 = stream.toList(); // immutable list
list1.add("new"); // works
list2.add("new"); // throws UnsupportedOperationException
Thus, the main difference lies in the mutability of the returned list and ease of use.