我在Java中有八个HashMap,如下所示:
HashMap<String, Double> map1= new HashMap<String, Double>();
HashMap<String, Double> map2= new HashMap<String, Double>();
HashMap<String, Double> map3= new HashMap<String, Double>();
HashMap<String, Double> map4= new HashMap<String, Double>();
HashMap<String, Double> map5= new HashMap<String, Double>();
HashMap<String, Double> map6= new HashMap<String, Double>();
HashMap<String, Double> map7= new HashMap<String, Double>();
HashMap<String, Double> map8= new HashMap<String, Double>();
我想将所有内容合并到一个新的HashMap中,比如new_MAP。我该怎么做?
我不确定我是否正确地回答了你的问题,Map接口中有一个putAll((方法,你可以通过这个方法将它们全部合并到新的HashMap中
例如:
Map<K,V> nhm = new HashMap<>();
nhm.putAll(map1);
...........
...........
nhm.putAll(map8);
然后决定如何处理重复的密钥,并使用Collectors#tomap的第三个参数:(Collectors.tomap(keyMapper,valueMapper,mergeFunction((
Stream.of(map1, map2,map3,map4, map4,map5,map6,map7,map8)
.flatMap(m -> m.entrySet().stream())
.collect(Collectors.toMap(
Entry::getKey, Entry::getValue, (oldValue, newValue) -> newValue
)
);
例如,如果重选了重复项,则上面的值将保留上次看到的值。您可以根据自己的要求将其更改为您想要的任何内容:
保持看到的第一个值:(oldValue,newValue(->oldValue
将两者合并,例如通过添加它们:(oldValue,newValue(->old+new
将两者合并,例如将它们相乘:(oldValue,newValue(->old*new
删除值:(oldValue,newValue(->空
您可以组合使用RIPAN的putAll
和厄立特里亚的Stream.of
进行简单的putAll:
HashMap<String, Double> NEW_MAP= new HashMap<String, Double>();
Stream.of(map1, map2,map3,map4, map4,map5,map6,map7,map8)
.forEach(NEW_MAP::putAll);
但是,如果您希望在合并重复密钥时使用一些自定义逻辑,您可以执行以下操作(例如选择最小值(:
HashMap<String, Double> NEW_MAP= new HashMap<String, Double>();
Stream.of(map1, map2,map3,map4, map4,map5,map6,map7,map8)
.flatMap(m -> m.entrySet().stream())
.forEach(e -> NEW_MAP.merge(e.getKey(), e.getValue(),
(v1, v2) -> Math.min(v1, v2)
));