Java Reference
In-Depth Information
The first version of the reduce() method takes an identity and an accumulator as arguments and reduces the
stream to a single value of the same type. You can rewrite the example of computing the sum of integers in a list
as follows:
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5);
int sum = numbers.stream()
.reduce(0, Integer::sum);
System.out.println(sum);
15
Let's attempt to do the same with the second example that computes the sum of the incomes.
double sum = Person.persons()
.stream()
.reduce(0.0, Double::sum);
The code generates the following compile-time error. Only the relevant part of the error message is shown.
error: no suitable method found for reduce(double,Double::sum)
.reduce(0.0, Double::sum);
^
method Stream.reduce(Person,BinaryOperator<Person>) is not applicable
(argument mismatch; double cannot be converted to Person) ...
The stream() method in Person.persons().stream() returns a Stream<Person> , and therefore, the reduce()
method is supposed to perform a reduction on Person object. However, the first argument to the method is 0.0,
which implies that the method is attempting to operate on the type Double , not the type Person . This mismatch in the
expected argument type Person and the actual argument type Double resulted in the error.
You wanted to compute the sum of the incomes of all people. You need to map the stream of people to a stream
of their incomes using the map operation as follows:
double sum = Person.persons()
.stream()
. map(Person::getIncome)
.reduce(0.0, Double::sum);
System.out.println(sum);
26000.0
Performing a map-reduce operation is typical in functional programming. The second version of the reduce
method, shown again for easy reference, lets you perform a map operation, followed by a reduce operation.
<U> U reduce(U identity, BiFunction<U,? super T,U> accumulator,
BinaryOperator<U> combiner)
 
Search WWH ::




Custom Search