Java Reference
In-Depth Information
Listing 13-7.
Collecting Results into a Collection
// CollectTest.java
package com.jdojo.streams;
import java.util.List;
import java.util.stream.Collectors;
public class CollectTest {
public static void main(String[] args) {
List<String> sortedNames = Person.persons()
.stream()
.map(Person::getName)
.sorted()
.collect(Collectors.toList());
System.out.println(sortedNames);
}
}
[Chris, Donna, Jeff, Ken, Laynie, Li]
Collecting Summary Statistics
In a data-centric application, you need to compute the summary statistics on a group of numeric data. For example,
you may want to know the maximum, minimum, sum, average, and count of the incomes of all people. The
java.util
package contains three classes to collect statistics:
DoubleSummaryStatistics
•
LongSummaryStatistics
•
IntSummaryStatistics
•
These classes do not necessarily need to be used with streams. You can use them to compute the summary
statistics on any group of numeric data. Using these classes is simple: create an object of the class, keep adding
numeric data using the
accept()
method, and finally, call the getter methods such as
getCount()
,
getSum()
,
getMin()
,
getAverage()
, and
getMax()
to get the statistics for the group of data. Listing 13-8 shows how to compute
the statistics on a number of
double
values.
Listing 13-8.
Computing Summary Statistics on a Group of Numeric Data
// SummaryStats.java
package com.jdojo.streams;
import java.util.DoubleSummaryStatistics;
public class SummaryStats {
public static void main(String[] args) {
DoubleSummaryStatistics stats = new DoubleSummaryStatistics();
stats.accept(100.0);
stats.accept(500.0);
stats.accept(400.0);