Search code examples
javaiteratorkey-valuetreemap

compareing and merging two TreeMaps


I have produced two multimaps in Java like this:

TreeMap1 = {key1=[a,b,c], key2=[d,e,f]}
TreeMap2 = {key1=[j,k], key2=[z,p]}

How can I add the values of TreeMap2, with similar key as in TreeMap1, to the values of TreeMap1, and produce a third TreeMap Like:

TreeMap3 =  {key1=[a,b,c,j,k], key2=[d,e,f,z,p]}

This Method gives me nothing.

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;  
}

Solution

  • Something like this?

    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;