Collectors.toCollection() for Specific Collection Types
What you'll learn: How to collect stream elements into a precise collection implementation of your choice, rather than accepting the default one.
Why You Need This
So far, you've used Collectors.toList() and Collectors.toSet(), which give you some implementation—but which one exactly? An ArrayList? A HashSet? The JDK decides for you. Sometimes you need full control over the exact collection type: maybe you want a LinkedList for constant-time insertions, a TreeSet for sorted uniqueness, or even a custom collection class.
Collectors.toCollection() lets you specify exactly which collection implementation to use.
How It Works
toCollection() takes a Supplier that produces an empty collection. Think of it as handing the stream a factory: "Here's how to create the collection you should fill."
The syntax looks like this:
.collect(Collectors.toCollection(ArrayList::new))
The ArrayList::new is a constructor reference—a supplier that creates a fresh ArrayList each time it's called.
Common Use Cases
ArrayList (when you want guaranteed ArrayList behavior):
List<String> list = stream.collect(Collectors.toCollection(ArrayList::new));
LinkedList (when you need different performance characteristics):
LinkedList<String> linkedList = stream.collect(Collectors.toCollection(LinkedList::new));
TreeSet (when you want sorted, unique elements):
TreeSet<Integer> treeSet = stream.collect(Collectors.toCollection(TreeSet::new));
Custom collections:
MyCustomList<String> custom = stream.collect(Collectors.toCollection(MyCustomList::new));
Key Takeaway: Use Collectors.toCollection() whenever you need a specific collection implementation rather than accepting the default provided by toList() or toSet()—pass a constructor reference to control exactly which collection type gets created.