[英]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
.我有一个类型为One
的值的 stream ,我想将它们减少为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).而且,我有一个BiFunction
器,它返回Sum
( Sum sum = transformer.apply(sum, one)
和一些逻辑)。 And have an initial value of Sum
( Sum.INITIAL
).并具有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 One
s.其中source
- One
的列表。 And have "Bad return type in lambda expression: Sum cannot be converted to One"
.并且有"Bad return type in lambda expression: Sum cannot be converted to One"
。
You need the combiner function as the third argument.您需要组合器 function 作为第三个参数。
source.stream().reduce(Sum.INITIAL,
(Sum sum, One one) -> transformer.apply(sum, one),
(Sum s1, Sum s2) -> {/*combine, e.g. return s1.add(s2)*/});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.