The Collectors class is a utility class in java.util.stream that provides ready-made implementations of the Collector interface, used with Stream.collect() to perform common reduction and aggregation operations on stream elements.
Key Points: • Collectors.toList(), toSet(), and toMap() convert a stream back into standard collection types. • Collectors.groupingBy() partitions elements into a Map based on a classifier function, useful for category-style grouping. • Collectors.joining() concatenates String elements, optionally with a delimiter, prefix, and suffix. • Collectors.counting(), summingInt(), and averagingDouble() compute aggregate statistics over a stream. • Multiple collectors can be composed with Collectors.collectingAndThen() for post-processing the collected result.
Example: Given a list of employees, employees.stream().collect(Collectors.groupingBy(Employee::getDepartment)) groups employees into a Map<String, List<Employee>> keyed by department name.
Code Example:
List<String> names = Arrays.asList("Amit", "Bala", "Amol", "Ravi");
Map<Character, List<String>> byFirstLetter = names.stream()
.collect(Collectors.groupingBy(n -> n.charAt(0)));
System.out.println(byFirstLetter);Interview Tip: A concise interview answer is:
"Collectors is a utility class that supplies ready-made collector implementations for Stream.collect(), like toList(), groupingBy(), and joining(). It lets me turn a stream into a collection, group or partition elements, or compute aggregates like counts and sums, without writing custom reduction logic."