Collectors.toList() is a built-in Collector, used with Stream.collect(), that gathers the elements of a stream into a new mutable List — typically the most common way to turn stream results back into a familiar collection type.
Key Points: • It's passed as the argument to collect(), e.g. stream.collect(Collectors.toList()), rather than being called directly on the stream. • The concrete List implementation returned is unspecified by the API — in practice it's usually an ArrayList, but code shouldn't depend on that. • It's commonly the final step in a pipeline after filter(), map(), or sorted() have transformed the data. • Java 16 introduced Stream.toList() as a shorter alternative, though Collectors.toList() remains the standard for pre-Java 16 codebases. • Related collectors like Collectors.toUnmodifiableList() (Java 10+) produce an immutable list when mutability isn't needed.
Example: names.stream().filter(n -> n.startsWith("A")).collect(Collectors.toList()) filters names starting with "A" and gathers them into a new List<String>.
Code Example:
List<String> names = Arrays.asList("Amit", "Bala", "Anita", "Ravi");
List<String> aNames = names.stream()
.filter(n -> n.startsWith("A"))
.collect(Collectors.toList());
System.out.println(aNames); // [Amit, Anita]Interview Tip: A concise interview answer is:
"Collectors.toList() is what I pass to collect() to gather processed stream elements back into a List, usually as the last step after filtering, mapping, or sorting. It's the standard bridge between the Streams API and ordinary collections, though in Java 16+ Stream.toList() offers a shorter equivalent."