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)
试试这个
int i = list.stream()
.map(e -> (int) Math.pow(e, list.size()))
.reduce((x, y) -> x + y)
.get();
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2800 次 |
最近记录: |