Streams: Collectors.toCollection targets a specific collection, like TreeSet

toCollection takes a Supplier for the target container, so a stream can be collected straight into a TreeSet, LinkedList or any other collection instead of the default ArrayList or HashSet.

Code
List<String> names = List.of("Bo", "Amy", "Cid", "Amy");
TreeSet<String> sorted = names.stream()
        .collect(Collectors.toCollection(TreeSet::new));
System.out.println("Sorted, deduped: " + sorted);
LinkedList<String> asLinked = names.stream()
        .collect(Collectors.toCollection(LinkedList::new));
System.out.println("As LinkedList: " + asLinked);
Output
Sorted, deduped: [Amy, Bo, Cid]
As LinkedList: [Bo, Amy, Cid, Amy]
Advertisement
More in JAVA

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-09-27

© Java Coding Hub · About · Contact · Privacy · Terms