Java Reference
In-Depth Information
else {
System.out.println("Could not get the highest earner.");
}
Highest earner: (3, Donna, FEMALE, 1962-07-29, 8700.00)
The following snippet of code prints the income of the highest income in the person list using the max() method
of the DoubleStream :
OptionalDouble income = Person.persons()
.stream()
.mapToDouble(Person::getIncome)
.max();
if (income.isPresent()) {
System.out.println("Highest income: " + income.getAsDouble());
}
else {
System.out.println("Could not get the highest income.");
}
Highest income: 8700.0
How will you get the highest earner among males and the highest among females in one stream pipeline? So far, you
have learned how to compute a single value using the reduce operation. In this case, you will need to group the people
into two groups, males and females, and then compute the person with the highest income in each group. I will show
you how to perform grouping and collect multiple values when I discuss the collect() method in the next section.
Streams support a count operation through the count() method that simply returns the number of elements in
the stream as a long . The following snippet of code prints the number of elements in the stream of people:
long personCount = Person.persons()
.stream()
.count();
System.out.println("Person count: " + personCount);
Person count: 6
The count operation is a specialized reduce operation. Were you thinking of using the map() and reduce()
methods to count the number of elements in a stream? The easier way is to map each element in the stream to 1 and
compute the sum. This approach does not use the reduce() method. Here is how you do this:
long personCount = Person.persons()
.stream()
.mapToLong(p -> 1L)
.sum();
 
Search WWH ::




Custom Search