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());
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
