Collectors.toList(): Collecting Stream Elements into a List
What you'll learn: How Collectors.toList() gathers all stream elements into a mutable ArrayList while preserving their order.
The Core Idea
Think of a stream as items flowing down a conveyor belt. Collectors.toList() is like having a worker at the end who catches each item in the order it arrives and places them into a box (an ArrayList). Once the stream finishes, you have a complete, ordered collection of all the elements.
The toList() collector is one of the most commonly used collectors because lists are versatile: they maintain insertion order, allow duplicates, and support indexed access.
How It Works
When you call collect(Collectors.toList()), the Streams API:
- Creates a new mutable
ArrayList - Accumulates each stream element into this list in encounter order
- Returns the populated list as the final result
Order Preservation
Unlike toSet(), which may not preserve order, toList() always maintains the order in which elements appear in the stream. If your stream processes elements [3, 1, 4, 1, 5], your resulting list will contain exactly [3, 1, 4, 1, 5].
When to Use toList()
Choose toList() when you:
- Need to preserve the order of stream elements
- Want to allow duplicate values
- Require a mutable collection you can modify after collection
- Need indexed access to elements later
Since you've already learned about toCollection(), remember that toList() is simply a convenience method—it's equivalent to collect(Collectors.toCollection(ArrayList::new)), but shorter and clearer.
Key Takeaway: Collectors.toList() collects stream elements into a mutable ArrayList, preserving their order and allowing duplicates—making it the go-to choice for most general-purpose stream collection needs.