Java Reference
In-Depth Information
else {
System.out.println("max is not defined.");
}
max is not defined.
The following snippet of code prints the details of the highest earner in the person's list:
Optional<Person> person = Person.persons()
.stream()
.reduce((p1, p2) -> p1.getIncome() > p2.getIncome()?p1:p2);
if (person.isPresent()) {
System.out.println("Highest earner: " + person.get());
}
else {
System.out.println("Could not get the highest earner.");
}
Highest earner: (3, Donna, FEMALE, 1962-07-29, 8700.00)
To compute the sum, max, min, average, etc. of a numeric stream, you do not need to use the
reduce()
method. You can map the non-numeric stream into one of the three numeric stream types (
IntStream
,
LongStream
,
or
DoubleStream
) and use the specialized methods for these purposes. The following snippet of code prints the
sum of the incomes of all people. Note the use of the
mapToDouble()
method that converts a
Stream<Person>
to a
DoubleStream
. The
sum()
method is called on the
DoubleStream
.
double totalIncome = Person.persons()
.stream()
.mapToDouble(Person::getIncome)
.sum();
System.out.println("Total Income: " + totalIncome);
Total Income : 26000.0
To get the minimum and maximum values of a stream, use the
min()
and
max()
methods of the specific stream.
These methods in the
Stream<T>
interface take a
Comparator
as argument and return an
Optional<T>
. They do not
take any arguments in
IntStream
,
LongStream
, and
DoubleStream
interfaces and return
OptionalInt
,
OptionalLong
,
and
OptionalDouble
, respectively. The following snippet of code prints the details of the highest earner in a list of
people:
Optional<Person> person = Person.persons()
.stream()
.max(Comparator.comparingDouble(Person::getIncome));
if (person.isPresent()) {
System.out.println("Highest earner: " + person.get());
}