Gio*_*ano 1 java lambda hashmap
我正在处理以下结构.
Map<String, HashMap<Integer, HashMap<Integer, Integer>>> ...
Run Code Online (Sandbox Code Playgroud)
我想用内部HashMap中的值递增一个计数器.我可以通过迭代函数或嵌套循环轻松完成.但是,我正在寻找使用lambdas的优雅解决方案.
您可以使用.values().stream()以获取a Stream中的值Map.然后你可以重复申请.flatMap,以便剥离嵌套结构,直到你得到一个Stream<Integer>.然后,您可以创建一个IntStream使用.mapToInt来获取.sum()所有值.
int sum = outerMostMap.values().stream() // HashMap<Integer, HashMap<Integer, Integer>>
.flatMap(map -> map.values().stream()) // HashMap<Integer, Integer>
.flatMap(map -> map.values().stream()) // Integer
.mapToInt(Integer::intValue) // int
.sum();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
70 次 |
| 最近记录: |