Why is a combiner needed for reduce method that converts type in java 8

I’m having trouble fully understanding the role that the combiner fulfills in Streams reduce method.

For example, the following code doesn’t compile:

int length = asList("str1", "str2").stream()
            .reduce(0, (accumulatedInt, str) -> accumulatedInt + str.length());

Compile error says :
(argument mismatch; int cannot be converted to java.lang.String)

but this code does compile:

int length = asList("str1", "str2").stream()  
    .reduce(0, (accumulatedInt, str ) -> accumulatedInt + str.length(), 
                (accumulatedInt, accumulatedInt2) -> accumulatedInt + accumulatedInt2);

I understand that the combiner method is used in parallel streams – so in my example it is adding together two intermediate accumulated ints.

But I don’t understand why the first example doesn’t compile without the combiner or how the combiner is solving the conversion of string to int since it is just adding together two ints.

Can anyone shed light on this?

4 Answers
4

Leave a Comment