会预料到
.reduce
将中间值存储在变量中
digitProduct
而不是数组成员本身。
减少
不将中间值存储在
digitalProduct
,但它也不将它们存储在“数组成员”中。
问题是
Arrays.stream(digitArray)
创建
IntStream
,不是
LongStream
。有多个过载
Array.stream
(
1
,
2
). 需要一个
int[]
返回
IntStream
而那个需要
long[]
返回一个
LongStream
.
IntStream.reduce
采取
IntBinaryOperator
和
LongStream.reduce
采取
LongBinaryOperator
.
它溢出的原因是您传递的lambda的返回类型为
int
在里面
.reduce(1, (x, y) -> x * y);
,lambda
(x, y) -> x * y
预计需要两个
int
s并返回
int
和
这
在哪里
*
溢出。它与数组的类型或将结果分配给的变量的类型无关
IntStream.reduce
,与一起工作
int
s
您不需要创建
长的
。您可以转换
IntStream
到
LongStream
打电话之前
reduce
.
Arrays.stream(digitArray)
.asLongStream()
.reduce(1, (x, y) -> x * y);