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);
The result of this operation should be 1*1*1 + 2*2*2 + 3*3*3 = 36. But instead I get i = 756. What's wrong? What should I change in order reduce() to work correctly?
The solution was already posted, but you get 756,
because the first call to reduce (x,y) with (1,2) is
1^3+2^3=9
then you reduce with (x,y) with (9,3)
9^3+3^3=756
BTW, since exponentiation is not associative, you can also get other values. For example, when using a parallel stream, I also got 42876
as result.
You don't even need to reduce
List<Integer> list = Arrays.asList(1, 2, 3);
int i = list.stream()
.mapToInt(e -> (int) Math.pow(e, list.size()))
.sum();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With