使用 Java 的 Stream.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);

该运算的结果应为1*1*1 + 2*2*2 + 3*3*3 = 36。但我得到I = 756。怎么了?为了使reduce()正确工作,我应该改变什么?

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

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

1^3+2^3=9

则用(x,y)还原为(9,3)

9^3+3^3=756

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

你甚至不需要减少

List<Integer> list = Arrays.asList(1, 2, 3);
int i = list.stream()
         .mapToInt(e -> (int) Math.pow(e, list.size()))
         .sum();

试试这个

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

也可以用collect(Collectors.summingInt(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);

你的逻辑是错误的,所以你得了756分

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

最新更新