Ale*_*rev 4 java functional-programming java-8
我想在List<Integer>via reduce中总结所有元素.
在Scala我可以写
val result = list.reduce(_ + _)
Run Code Online (Sandbox Code Playgroud)
有没有办法在Java8中以这种简洁的方式编写此操作?或者我应该这样写?
int result = list.reduce((x,y) -> x + y));
Run Code Online (Sandbox Code Playgroud)
如果您特别想使用reduce,则会执行以下操作:
list.stream().reduce(0, Integer::sum); // will return zero if list is empty
list.stream().reduce(Integer::sum).get(); // will throw an exception if list is empty
Run Code Online (Sandbox Code Playgroud)
由于求和很常见,有几种方法可以做到:
list.stream().mapToInt(x->x).sum(); // mapToInt makes an IntStream
list.stream().collect(summingInt(x->x)); // using a collector
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
104 次 |
| 最近记录: |