Pro*_*3cy 5 java hashmap java-8 java-stream collectors
我想将a转换Map<String,Map<String,Integer>>为Map<String,Integer>using Stream。
这是要注意的问题(以及为什么我似乎无法弄清楚):
我想将我的Integer-Values按相应Map的键-值进行分组。因此,澄清一下:
我有这样的条目:
Entry 1: ["A",["a",1]]
Entry 2: ["B",["a",2]]
Entry 3: ["B",["b",5]]
Entry 4: ["A",["b",0]]
Run Code Online (Sandbox Code Playgroud)
我想将该结构转换为以下内容:
Entry 1: ["a",3]
Entry 2: ["b",5]
Run Code Online (Sandbox Code Playgroud)
我认为,使用Collectors类似的类和方法summingInt,groupingBy您应该能够完成此任务。不过,我似乎无法找出解决此问题的正确方法。
应该注意Map的是,保证所有的内部s始终具有相同的键,其Integer-value 0或sth>0。(例如,“ A”和“ B”都将始终具有彼此相同的5个键)到目前为止,我已经尝试了很多。我知道,如果没有求和部分,我可以这样:
Map<String,Integer> map2= new HashMap<String,Integer>();
map1.values().stream().forEach(map -> {
map2.putAll(map.entrySet().stream().collect(Collectors.toMap(entry -> entry.getKey(), entry -> entry.getValue())));
});
Run Code Online (Sandbox Code Playgroud)
但是如何添加求和部分呢?
这应该工作:
首先创建Stream所有内部映射的条目,然后按键对条目进行分组,并对具有相同键的值求和。
Map<String,Integer> map2 =
map1.values()
.stream()
.flatMap(m -> m.entrySet().stream()) // create a Stream of all the entries
// of all the inner Maps
.collect(Collectors.groupingBy(Map.Entry::getKey,
Collectors.summingInt(Map.Entry::getValue)));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
79 次 |
| 最近记录: |