What is custom collectors in Java?

Custom collectors in Java allow developers to create their own implementations of the Collector interface, which can be used to aggregate the results of a Stream in a specific way that is not provided by the standard collectors. This provides a powerful mechanism to customize the behavior of reduction operations in Java Stream API.

By implementing custom collectors, you can define how to accumulate elements, combine results, and finish the collection process, making it flexible for diverse use cases such as distinct filtering, grouping, and complex data transformations.

Here’s an example of creating a custom collector that collects elements into a List and counts the total number of elements:

import java.util.List; import java.util.ArrayList; import java.util.stream.Collector; import java.util.stream.Collectors; public class CustomCollectorExample { public static void main(String[] args) { List names = List.of("Alice", "Bob", "Charlie", "David"); // Custom Collector to collect names and count them Collector, String> customCollector = Collector.of( ArrayList::new, List::add, (left, right) -> { left.addAll(right); return left; }, list -> "Names: " + list.toString() + " Count: " + list.size() ); String result = names.stream().collect(customCollector); System.out.println(result); } }

Custom Collectors Java Stream API Java Collectors Java Programming Stream Operations