Maksim Maltsev
Maksim Maltsev

Reputation: 43

How to use stream reduce with different types?

I have a stream of values with type One and I want to reduce them to a value of type, Sum. (it's not integers, just for example). And, I have a BiFunction summator which returns Sum (Sum sum = transformer.apply(sum, one) with some logic). And have an initial value of Sum (Sum.INITIAL).

Tried to do something like:

source.stream().reduce(Sum.INITIAL, (Sum sum, One one) -> transformer.apply(sum, one));

where source - list of Ones. And have "Bad return type in lambda expression: Sum cannot be converted to One".

Upvotes: 4

Views: 1391

Answers (1)

Unmitigated
Unmitigated

Reputation: 89194

You need the combiner function as the third argument.

source.stream().reduce(Sum.INITIAL, 
    (Sum sum, One one) -> transformer.apply(sum, one),
    (Sum s1, Sum s2) -> {/*combine, e.g. return s1.add(s2)*/});

Upvotes: 4

Related Questions