How to use stream reduce with different types?

Viewed 261

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".

1 Answers

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)*/});
Related