How to Use Collectors.toList in Java: Simple Guide
In Java,
Collectors.toList() is used with streams to collect elements into a List. You apply it by calling stream().collect(Collectors.toList()) on a collection or array to get a new list of elements.Syntax
The basic syntax to use Collectors.toList() is:
stream(): Converts a collection or array into a stream of elements.collect(): A terminal operation that gathers elements from the stream.Collectors.toList(): A collector that accumulates the stream elements into aList.
java
List<Type> list = collection.stream().collect(Collectors.toList());
Example
This example shows how to convert a list of strings to uppercase and collect them into a new list using Collectors.toList().
java
import java.util.List; import java.util.stream.Collectors; import java.util.Arrays; public class CollectorsToListExample { public static void main(String[] args) { List<String> names = Arrays.asList("alice", "bob", "charlie"); List<String> upperNames = names.stream() .map(String::toUpperCase) .collect(Collectors.toList()); System.out.println(upperNames); } }
Output
[ALICE, BOB, CHARLIE]
Common Pitfalls
Common mistakes when using Collectors.toList() include:
- Expecting the returned list to be mutable or of a specific implementation (it may be unmodifiable or any List type).
- Using
toList()without a stream, which causes errors. - Not importing
java.util.stream.Collectors.
Always remember that Collectors.toList() returns a new list and does not modify the original collection.
java
import java.util.List; import java.util.stream.Collectors; import java.util.Arrays; public class WrongUsage { public static void main(String[] args) { List<String> names = Arrays.asList("alice", "bob"); // Wrong: calling toList() directly on collection // List<String> list = names.collect(Collectors.toList()); // Compile error // Right way: List<String> list = names.stream().collect(Collectors.toList()); System.out.println(list); } }
Output
[alice, bob]
Quick Reference
| Method | Description |
|---|---|
| stream() | Creates a stream from a collection or array |
| collect() | Terminal operation to gather stream elements |
| Collectors.toList() | Collector that accumulates elements into a List |
Key Takeaways
Use Collectors.toList() with stream().collect() to convert streams into lists.
Collectors.toList() returns a new list and does not modify the original collection.
Always import java.util.stream.Collectors to use Collectors.toList().
Do not call toList() directly on collections without stream().
The returned list type is not guaranteed to be mutable or a specific implementation.