[英]Count over nested HashMaps with lambda
I am dealing with the following structure. 我正在处理以下结构。
Map<String, HashMap<Integer, HashMap<Integer, Integer>>> ...
I would like to increment a counter with the values in the inner HashMap. 我想用内部HashMap中的值增加一个计数器。 I could easily do that with an iterative function or with nested loop.
我可以使用迭代函数或嵌套循环轻松地做到这一点。 However, I am looking for an elegant solution using lambdas.
但是,我正在寻找使用lambda的优雅解决方案。
You can use .values().stream()
in order to get a Stream
of the values in a Map
. 您可以使用
.values().stream()
来获取Map
值的Stream
。 Then you can repeatedly apply .flatMap
in order to peel away the nested structures until you get a Stream<Integer>
. 然后,您可以重复应用
.flatMap
以便剥离嵌套结构,直到获得Stream<Integer>
为止。 Then you can create an IntStream
using .mapToInt
to get the .sum()
of all the values. 然后,您可以使用
.mapToInt
创建一个IntStream
以获取所有值的.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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.