解密流减少功能 [英] Deciphering Stream reduce function
问题描述
为什么 c1
和 c2
不会被视为两个字符串,而是一个字符串
和一个整数
?
Why are both c1
and c2
are not seen as two Strings but instead one String
and one Integer
?
Arrays.asList("duck","chicken","flamingo","pelican")
.stream()
.reduce(0,
(c1, c2) -> c1.length() + c2.length(),
(s1, s2) -> s1 + s2);
推荐答案
三个变种的 reduce
方法,它们的签名和返回类型不同。如果你看一下 reduce
具有此签名:
There are three variations of the reduce
method, which differ by their signatures and return types. if you look at the overload for reduce
which has this signature:
reduce(U identity, BiFunction<U,? super T,U> accumulator, BinaryOperator<U> combiner)
从方法签名中可以看出, reduce
有3个参数 identity ,累加器和组合器。身份值是您传入 reduce
ie( 0
)的初始值,然后我们有累加器基本上将一个额外的元素合并到一个结果中,最后,组合器的工作是组合提供的两个值。
As you can see from the method signature this overload of reduce
has 3 parameters the identity, accumulator and a combiner. The identity value is the initial value you've passed into reduce
i.e (0
), we then have the accumulator which basically incorporates an additional element into a result and finally, the combiner whos job is to combine the two values provided.
所以你问:
为什么c1和c2都不被视为两个字符串而是一个
字符串和一个整数?
Why are both c1 and c2 are not seen as two Strings but instead one String and one Integer?
BiFunction
的第一个参数是 U
在你的情况下是 Integer
因此,用于身份值的类型必须与第一个参数的类型相同,以及累加器函数的返回类型( BiFunction
)。
The first argument to BiFunction
is U
which in your case is Integer
so, therefore, the type used for the identity value must be the same type of the first argument as well as the return type of the accumulator function (BiFunction
).
除此之外,你需要改变这个:
That aside, you'll need to change this:
(c1, c2) -> c1.length() + c2.length()
到此:
(c1, c2) -> c1 + c2.length()
重要的是要注意组合器功能 (s1,s2) - >根本不会调用s1 + s2
。原因是此特定重载被设计为与 parallelStream
一起使用,因此为了使组合器工作,流必须并行。否则,只会调用累加器函数。
it's important to note that the combiner function (s1, s2) -> s1 + s2
will not be called at all. Reason being that this specific overload was designed to be used with parallelStream
, so in order for a combiner to work, a stream must be parallel. Otherwise, just the accumulator function will be called.
作为一方,您的完整代码可以简化为:
as an side, your full code can be simplified to:
int result = Stream.of("duck","chicken","flamingo","pelican")
.reduce(0,
(c1, c2) -> c1 + c2.length(),
(s1, s2) -> s1 + s2);
如果你想避免装箱/拆箱的开销,那就更好了减少
:
int result = Stream.of("duck", "chicken", "flamingo", "pelican")
.mapToInt(String::length)
.sum();
这篇关于解密流减少功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!