我在Java中生成了两个这样的多图:
TreeMap1 = {key1=[a,b,c], key2=[d,e,f]}
TreeMap2 = {key1=[j,k], key2=[z,p]}
如何将TreeMap2的值(与TreeMap1中的键类似)添加到TreeMap1的值中,并生成第三个TreeMap,如:
TreeMap3 = {key1=[a,b,c,j,k], key2=[d,e,f,z,p]}
这个方法什么也没给我。
public TreeMap<String, List<String>> make_TreeMap3(){
for(Entry<String,List<String>> entry_t1 :this.map_FuncType.entrySet()){
for(Entry<String,List<String>> entry_t2 : this.map_AufOrgUserField.entrySet()){
if(entry_t2.getKey().contains(entry_t1.getKey())){
entry_t2.getValue().addAll(entry_t1.getValue());
}
}
}
return map_mergOrgandType;
}
答案 0 :(得分:1)
这样的东西?
TreeMap<String, List<String>> treeMap3 = new TreeMap<>(treeMap1);
for (String k : treeMap3.keySet()) {
if (treeMap2.containsKey(k)) {
treeMap3.get(k).addAll(treeMap2.get(k));
}
}
return treeMap3;
答案 1 :(得分:0)
如果你愿意使用第三方库,那么Guava很容易做到。
public class MultimapMerge {
public static void main(String[] args) {
Multimap<String, String> map1 = TreeMultimap.create();
map1.put("key1", "a");
map1.put("key1", "b");
map1.put("key1", "c");
map1.put("key2", "d");
map1.put("key2", "e");
map1.put("key2", "f");
Multimap<String, String> map2 = TreeMultimap.create();
map2.put("key1", "j");
map2.put("key1", "k");
map2.put("key2", "z");
map2.put("key2", "p");
Multimap<String, String> map3 = TreeMultimap.create();
map3.putAll(map1);
map3.putAll(map2);
System.out.println(map3);
}
}
http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/collect/Multimap.html