使用Java的Stream.reduce()来计算功率总和会产生意外结果

sva*_*605 10 java-8 java-stream

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);
Run Code Online (Sandbox Code Playgroud)

这个操作的结果应该是1*1*1 + 2*2*2 + 3*3*3 = 36.但是我得到i = 756.怎么了?为了使reduce()正常工作,我应该更改什么?

use*_*547 18

该解决方案已经发布,但你得到了756,

因为用(1,2)第一次调用reduce(x,y)是

1^3+2^3=9
Run Code Online (Sandbox Code Playgroud)

那你用(x,y)减去(9,3)

9^3+3^3=756
Run Code Online (Sandbox Code Playgroud)

顺便说一句,由于取幂不是关联的,你也可以得到其他值.例如,当使用并行流时,我也得到了42876结果.


Ash*_*Ash 16

你甚至不需要减少

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

int i = list.stream()
         .mapToInt(e -> (int) Math.pow(e, list.size()))
         .sum();
Run Code Online (Sandbox Code Playgroud)

  • 从技术上讲,`sum()`仍然是一个减少,它只是API内置的一个 (8认同)
  • 最佳答案,最少的样板代码.比使用reduce更好,并且比使用collect更好(Collectors.summingInt) (3认同)

Lal*_*Rao 5

试试这个

int i = list.stream()
            .map(e -> (int) Math.pow(e, list.size()))
            .reduce((x, y) -> x + y)
            .get();
Run Code Online (Sandbox Code Playgroud)

  • `.reduce((x,y) - > x + y)`又名`sum()` (2认同)