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.
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);
Sorted, deduped: [Amy, Bo, Cid]
As LinkedList: [Bo, Amy, Cid, Amy]
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