-3

let's take an example :

Syntax :        
    Map<String,Map<String,String>> A = new HashMap<>();
    Map<String,Map<String,String>> B = new HashMap<>();
Implementation :
    Map<TableA,Map<AID,AVAL>> A = new HashMap<>();
    Map<TableB,Map<BID,BVAL>> B = new HashMap<>();

Compare HashMaps A & B based on the keys TableA and AID & TableB and BID

What is optimized way to iterate these hashmaps?

vinay kumar
  • 91
  • 1
  • 2
  • 10

3 Answers3

2

You should define a bit better what you mean with comparing the maps. You want to compare keys and values? You could make a copy of the second map, cycle on the first and remove the keys of the first from the copy of the second. The keys that are left from copy of the second are those in the second and not in the first. On the other hand, those in the first and not in the second, you won't find them in the cycle.

1

The two Maps do not necessarily have the same number of elements and a given map can have no elements. When we compare the two Maps, if the two Maps are equal then it is fine. If the two are unequal I want to identify (print) the elements that are in one Map but not the other map.

Map<String,String> map1 = new HashMap<String,String>();
        map1.put("A", "B");
        map1.put("C","D");
        map1.put("E","F");
        map1.put("E","G");


        Map<String,String> map2 = new HashMap<String,String>();
        map2.put("A", "B");
        map2.put("C","D");
        map2.put("E","F");
        map2.put("F","F");
        map2.put("G","G");

        if (map1.entrySet().containsAll(map2.entrySet())) {
              System.out.println("Map2 is a subset of Map1");
        }
        else {  // find map pairs that are in set 1 but not in set 2
                // expected result is key = E and value = G
        }

        if (map2.entrySet().containsAll(map1.entrySet())) {
              System.out.println("Map1 is a subset of Map2");
        }
        else {  // find map pairs that are in set 2 but not in set 1
               // expected result is key=F, value=F and key=G, value=G
        }

       //compare each entry of map
       for (final String key : map2.keySet()) {
           if (map1.containsKey(key)) {
                     System.out.println("Value:" + map1.get(key));
           }
       }
Ravindra Kumar
  • 1,842
  • 14
  • 23
1

I tried it, you have to go through keySet for TableA and TableB comparing


Iterator<Map.Entry<TableA ,Map<AID,AVAL>> itr1 = A.entrySet().iterator();
Iterator<Map.Entry<TableB ,Map<BID,BVAL>> itr2 = A.entrySet().iterator();
while(itr1.hasNext() && itr2.hasNext())
{
    Map.Entry<TableA ,Map<AID,AVAL>> entry1 = itr1.next();
    Map.Entry<TableB ,Map<BID,BVAL>> entry2 = itr2.next();
    if((entry1.getKey().equals(entry2.getKey())) 
    Sop("match");
    else Sop("Not FOund");
}
Tavash
  • 101
  • 1
  • 1
  • 7