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);
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?