Java Reference
In-Depth Information
// Get stats
long count = stats.getCount();
double sum = stats.getSum();
double min = stats.getMin();
double avg = stats.getAverage();
double max = stats.getMax();
System.out.printf("count=%d, sum=%.2f, min=%.2f, average=%.2f, max=%.2f%n",
count, sum, min, max, avg);
}
}
count=3, sum=1000.00, min=100.00, average=500.00, max=333.33
The summary statistics classes were designed to be used with streams. They contain a combine() method that
combines two summary statistics. Can you guess its use? Recall that you need to specify a combiner when you collect
data from a stream and this method can act as a combiner for two summary statistics. The following snippet of code
computes the summary statistics for incomes of all people:
DoubleSummaryStatistics incomeStats =
Person.persons()
.stream()
.map(Person::getIncome)
.collect(DoubleSummaryStatistics::new,
DoubleSummaryStatistics::accept,
DoubleSummaryStatistics::combine);
System.out.println(incomeStats);
DoubleSummaryStatistics{count=6, sum=26000.000000, min=0.000000, average=4333.333333, max=8700.000000}
The Collectors class contains methods to obtain a collector to compute the summary statistics of the specific
type of numeric data. The methods are named summarizingDouble() , summarizingLong() , and summarizingInt() .
They take a function to be applied on the elements of the stream and return a DoubleSummaryStatistics , a
LongSummaryStatistics , and an IntSummaryStatistics , respectively. You can rewrite the code for the previous
example as follows:
DoubleSummaryStatistics incomeStats =
Person.persons()
.stream()
.collect(Collectors.summarizingDouble(Person::getIncome));
System.out.println(incomeStats);
DoubleSummaryStatistics{count=6, sum=26000.000000, min=0.000000, average=4333.333333, max=8700.000000}
The Collectors class contains methods such as counting() , summingXxx() , averagingXxx() , minBy() , and
maxBy() that return a collector to perform a specific type of summary computation on a group of numeric data what
you get in one shot using the summarizingXxx() method. Here, Xxx can be Double , Long , and Int .
Search WWH ::




Custom Search