use*_*934 5 java lambda java-8 java-stream
给定一个Map<Long, Integer>,使用Java 8 Map Stream,您如何计算总数
Long result变量中所有条目的总和?
例如:[{100:1}, {100,2}]
result =(100 * 1)+(100 * 2)= 300
这就是我使用迭代的方式:
Map<Long, Integer> map = //init map
Long sum = 0;
for (Map.Entry<String, String> entry : map.entrySet()) {
sum+= (entry.getKey() * entry.getValue());
}
Run Code Online (Sandbox Code Playgroud)
我在想一些事情:
map.entrySet().stream()
.forEach(entry -> entry.getKey() * entry.getValue())
.sum()
Run Code Online (Sandbox Code Playgroud)
这应该可以解决问题。
long sumOfProducts = map.entrySet().stream().mapToLong(e -> e.getKey() * e.getValue()).sum();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
73 次 |
| 最近记录: |