Collectors.toCollection(): Custom Collection Types
What you'll learn: How to collect stream elements into a specific collection implementation of your choice using toCollection().
Why toCollection() Exists
So far you've used toList() and toSet(), but Java gives you the default implementation—you don't control which specific List or Set type you get. What if you need a LinkedList for fast insertions at both ends? Or a TreeSet for automatic sorting? That's where toCollection() comes in.
The Core Idea
Collectors.toCollection() accepts a supplier function that creates the exact collection type you want. Think of it as saying: "Here's the empty container I want—now fill it with my stream elements."
The signature looks like this:
toCollection(Supplier<C> collectionFactory)
You pass a constructor reference or lambda that produces a new, empty collection.
Basic Examples
Want a LinkedList instead of a generic List?
List<String> linkedList = stream()
.filter(s -> s.length() > 3)
.collect(Collectors.toCollection(LinkedList::new));
Need a TreeSet for automatic sorting and uniqueness?
Set<Integer> treeSet = stream()
.map(String::length)
.collect(Collectors.toCollection(TreeSet::new));
Want a custom deque for stack-like operations?
Deque<String> deque = stream()
.collect(Collectors.toCollection(ArrayDeque::new));
When to Use It
Use toCollection() when:
- You need specific performance characteristics (e.g.,
LinkedListfor frequent insertions) - You want sorted results (
TreeSet) - You require a specific collection interface like
DequeorQueue
Key Takeaway: Collectors.toCollection() gives you precise control over the collection implementation by letting you specify the exact container type through a supplier function.