Java Reference
In-Depth Information
Notice that the output has two top level groups based on gender: Male and Female. With each gender group,
there are nested groups based on the month of the person's birth. For each month group, you have a list of those born
in that month. For example, Ken and LI were born in the month of May and they are males, so they are listed in the
output together.
As the final example in this section, let's summarize the income of people grouped by gender. The program in
Listing 13-12 computes the summary statistics of income by gender. I have used static imports to use the method
names from the Collectors class to keep the code a bit cleaner. Looking at the output, you can tell the average
income of females is 25 dollars more than that of males. You can keep nesting groups inside another group. There is
no limit on levels of nesting for groups.
Listing 13-12. Summary Statistics of Income Grouped by Gender
// IncomeStatsByGender.java
package com.jdojo.streams;
import java.util.DoubleSummaryStatistics;
import java.util.Map;
import static java.util.stream.Collectors.groupingBy;
import static java.util.stream.Collectors.summarizingDouble;
public class IncomeStatsByGender {
public static void main(String[] args) {
Map<Person.Gender, DoubleSummaryStatistics> incomeStatsByGender =
Person.persons()
.stream()
.collect(groupingBy(Person::getGender,
summarizingDouble(Person::getIncome)));
System.out.println(incomeStatsByGender);
}
}
{MALE=DoubleSummaryStatistics{count=4, sum=17300.000000, min=1800.000000, average=4325.000000,
max=7100.000000}, FEMALE=DoubleSummaryStatistics{count=2, sum=8700.000000, min=0.000000,
average=4350.000000, max=8700.000000}}
Partitioning Data
Partitioning data is a special case of grouping data. Grouping data is based on the keys returned from a function. There
are as many groups as the number of distinct keys returned from the function. Partitioning groups data into two groups:
for one group a condition is true; for the other, the same condition is false. The partitioning condition is specified using
a Predicate . By now, you might have guessed the name of the method in the Collectors class that returns a collector
to perform the partitioning. The method is partitioningBy() . It is overloaded and it has two versions:
partitioningBy(Predicate<? super T> predicate)
partitioningBy(Predicate<? super T> predicate, Collector<?
super T,A,D> downstream)
 
Search WWH ::




Custom Search