Java 8 使用Java';s Stream.reduce()计算幂和会产生意外结果 List-List=Arrays.asList(1,2,3); int i=list.stream().mapToInt(e->e) .reduce((x,y)->(int)Math.pow(x,list.size())+(int)Math.pow(y,list.size()) .getAsInt(); 系统输出打印LN(i);

Java 8 使用Java';s Stream.reduce()计算幂和会产生意外结果 List-List=Arrays.asList(1,2,3); int i=list.stream().mapToInt(e->e) .reduce((x,y)->(int)Math.pow(x,list.size())+(int)Math.pow(y,list.size()) .getAsInt(); 系统输出打印LN(i);,java-8,java-stream,Java 8,Java Stream,此操作的结果应为1*1*1+2*2*2+3*3*3=36。但我得到的是I=756。发生了什么?要使reduce()正常工作,我应该更改什么?发现错误后,新代码如下: List<Integer> list = Arrays.asList(1, 2, 3); int i = list.stream().mapToInt(e -> e) .reduce((x, y) -> (int) Math.pow(x, list.size()) + (int) M

此操作的结果应为1*1*1+2*2*2+3*3*3=36。但我得到的是I=756。发生了什么?要使reduce()正常工作,我应该更改什么?

发现错误后,新代码如下:

List<Integer> list = Arrays.asList(1, 2, 3);

int i = list.stream().mapToInt(e -> e)
            .reduce((x, y) -> (int) Math.pow(x, list.size()) + (int) Math.pow(y, list.size()))
            .getAsInt();
        System.out.println(i);
List-List=Arrays.asList(1,2,3);
int i=list.stream().mapToInt(e->e)
.map(e->(int)Math.pow(e,list.size())
.减少((x,y)->x+y)
.getAsInt();
系统输出打印LN(i);

您也可以使用
collect(Collectors.summingit(Integer::intValue))
而不是
reduce((x,y)->x+y)
试试这个

List<Integer> list = Arrays.asList(1, 2, 3);

int i = list.stream().mapToInt(e -> e)
             .map(e -> (int) Math.pow(e, list.size()))
             .reduce((x, y) -> x + y)
             .getAsInt();
System.out.println(i);

你甚至不需要减少

int i = list.stream()
            .map(e -> (int) Math.pow(e, list.size()))
            .reduce((x, y) -> x + y)
            .get();
List-List=Arrays.asList(1,2,3);
int i=list.stream()
.mapToInt(e->(int)Math.pow(e,list.size())
.sum();

解决方案已经发布,但您得到756

因为用(1,2)减少(x,y)的第一个调用是

然后你用(x,y)和(9,3)来减少


顺便说一句,因为求幂不是关联的,所以还可以得到其他值。例如,当使用并行流时,我也得到了
42876

您的逻辑错误,这就是为什么得到756

9^3+3^3=756

最好的答案,最少的样板代码。比使用reduce更好,也比使用collect(collector.summingit)更好从技术上讲,
sum()
仍然是一种减少,它只是内置于API@RobV:当然可以,但“最少的样板代码数”只是指你要写多少代码才能达到目的。@Rob,是的,我想提一下,
sum()
只是一种专门的简化。它甚至提到总和是一种简化的形式,你的逻辑也是错误的。传递给
reduce
的函数没有关联性,因此,它只在顺序流中工作。您给出的示例是在顺序流中工作。所以我在几分钟内就写了,我没有给出任何例子。我只是一个读者,他告诉你,你使用流API的方式违反了合同,只是在某些情况下碰巧产生了预期的结果,这并不是一个正确的解决方案。仅供参考:我写的答案是我从oracle参考中记得的。Reduce绝对不会做你认为它做的事情。再次阅读文档:(特别是,检查累加器的参数)是的,我发现我误解了它。Reduce((x,y)->x+y)aka
sum()
@njzk2你需要
mapToInt
。当然,但在这种情况下你为什么不使用
mapToInt
1^3+2^3=9
9^3+3^3=756
int i = list.stream()
            .mapToInt(e -> e)
            .peek(System.out::println)
            .reduce(0,(x, y) -> x + (int) Math.pow(y, list.size()));