Java / Java 21 Interview Questions
What are the most important Collectors and how do you write custom ones?
Collectors define how a terminal collect() operation assembles the stream elements. java.util.stream.Collectors provides ~40 factory methods; the most frequently used in interviews are:
import static java.util.stream.Collectors.*;
// Grouping
Map> byCity =
people.stream().collect(groupingBy(Person::city));
// Grouping with downstream collector
Map countByCity =
people.stream().collect(groupingBy(Person::city, counting()));
Map avgAgeByCity =
people.stream().collect(groupingBy(Person::city, averagingInt(Person::age)));
// Partitioning — splits into true/false map
Map> adultMap =
people.stream().collect(partitioningBy(p -> p.age() >= 18));
// Joining
String csv = names.stream().collect(joining(", ", "[", "]"));
// e.g. "[Alice, Bob, Carol]"
// toMap
Map byId = people.stream()
.collect(toMap(Person::id, p -> p,
(existing, duplicate) -> existing)); // merge fn for duplicates
// teeing (Java 12) — two simultaneous collectors
record MinMax(int min, int max) {}
MinMax mm = IntStream.of(3, 1, 4, 1, 5, 9)
.boxed()
.collect(teeing(
minBy(Comparator.naturalOrder()),
maxBy(Comparator.naturalOrder()),
(min, max) -> new MinMax(min.get(), max.get())
));
// toUnmodifiableList/Set/Map — Java 10
List immutable = stream.collect(toUnmodifiableList());
More Related questions...