Java HashMap<String,List<String>>() Comparison

14,650

Solution 1

guava has Maps.difference(map1, map2)

Solution 2

HashMap.equals will tell you if they are identical (same keys and values) but the rest you will have to roll yourself.

You will need to iterate the keyset() of one HashMap, look for it in the keySet() of the other and if found then compare the values.

Then, you will have to do the reverse, looking for keys in the second that don't exist in the first. You can probably use Set methods for this.

Share:
14,650
Green
Author by

Green

Updated on June 19, 2022

Comments

  • Green
    Green almost 2 years

    I'm wondering the best way to compare these two HashMaps. I want to verify if they are the same, and if not, what is the difference. If it matters, then I'm wondering what the 2nd one has/does not have that the first hashmap does have. I'll need to know if one has a key the other does not, as well as the Value List differences per key. I'm hoping there is a simple way to map this, but not sure. Basic Example:

        HashMap<String, List<String>> hmOne = new HashMap<String, List<String>>();
        List<String>l1 = new ArrayList<String>();
    
        l1.add("one");
        l1.add("two");
        l1.add("three");
        l1.add("four");
        l1.add("five");
        hmOne.put("firstkey", l1);
        l1 = new ArrayList<String>();
    
        l1.add("1");
        l1.add("2");
        l1.add("3");
        l1.add("4");
        l1.add("5");
        hmOne.put("secondkey", l1);
    
        HashMap<String, List<String>> hmTwo = new HashMap<String, List<String>>();
        List<String>l2 = new ArrayList<String>();
        l2.add("one");
        l2.add("two");
        l2.add("four");
        l2.add("five");
        hmTwo.put("firstkey", l2);
        l2 = new ArrayList<String>();
    
        l2.add("1");
        l2.add("3");
        l2.add("4");
        l2.add("5");
        hmTwo.put("secondkey", l2);
    

    Thanks for any help.

  • Christoffer Hammarström
    Christoffer Hammarström over 12 years
    Easier to use the methods of mapOne.entrySet(): .containsAll(mapTwo.entrySet())/.removeAll(mapTwo.entrySet()‌​)/.retainAll(mapTwo.‌​entrySet()) than iterating manually. Possibly with a clone of mapOne since the methods are destructive.
  • Miserable Variable
    Miserable Variable over 12 years
    @ChristofferHammarström I mentioned the set methods for reverse but not for first because value comparison is also required.
  • Roland Illig
    Roland Illig over 12 years
    Guava also has Lists.newArrayList("1", "2", "3", "4", "5"), which will make the original code much shorter than it is right now.
  • Christoffer Hammarström
    Christoffer Hammarström over 12 years
    That's why you use .entrySet(), not .keySet().
  • Miserable Variable
    Miserable Variable over 12 years
    Oops yes. Sorry I was blind earlier.