Grouping collectors are part of the Java Stream API's Collectors
utility class. They allow you to group elements from a stream based on a specific criterion and perform various aggregation operations on the grouped elements. These collectors are particularly useful for creating maps or other data structures that organize data into groups.
Here are some commonly used grouping collectors:
Collectors.groupingBy(): This collector groups elements based on a classifier function and creates a map where the keys are the results of the classifier function and the values are lists of elements that match each key.
Example:
java
Map<String, List<Person>> peopleByCity = people.stream() .collect(Collectors.groupingBy(Person::getCity));
Collectors.groupingByConcurrent():
Similar to groupingBy()
, this collector groups elements concurrently, making it suitable for parallel processing.
Collectors.partitioningBy(): This collector divides elements into two groups (true and false) based on a predicate and creates a map with Boolean keys.
Example:
java
Map<Boolean, List<Person>> adultsAndMinors = people.stream()
.collect(Collectors.partitioningBy(p -> p.getAge() >= 18));
Collectors.toMap():
While not a grouping collector in the traditional sense, toMap()
can be used to group elements based on keys and values derived from the elements.
Example:
java
Map<String, Integer> nameToAge = people.stream() .collect(Collectors.toMap(Person::getName, Person::getAge));
Collectors.groupingBy with downstream collectors:
You can combine grouping collectors with downstream collectors like Collectors.counting()
, Collectors.summingInt()
, Collectors.mapping()
, etc., to perform more complex aggregations on the grouped elements.
Example:
java
Map<String, Long> countByCity = people.stream() .collect(Collectors.groupingBy(Person::getCity, Collectors.counting()));
These grouping collectors help you efficiently organize and analyze data based on specific criteria, making complex data manipulations more manageable. They are particularly useful when working with large datasets and performing aggregations on grouped data.
No comments:
Post a Comment