Search code examples
javadictionarycollectionscompareequals

How to compare two maps by their values


How to compare two maps by their values? I have two maps containing equal values and want to compare them by their values. Here is an example:

    Map a = new HashMap();
    a.put("foo", "bar"+"bar");
    a.put("zoo", "bar"+"bar");

    Map b = new HashMap();
    b.put(new String("foo"), "bar"+"bar");
    b.put(new String("zoo"), "bar"+"bar");

    System.out.println("equals: " + a.equals(b));            // obviously false

How should I change the code to obtain a true?


Solution

  • Your attempts to construct different strings using concatenation will fail as it's being performed at compile-time. Both of those maps have a single pair; each pair will have "foo" and "barbar" as the key/value, both using the same string reference.

    Assuming you really want to compare the sets of values without any reference to keys, it's just a case of:

    Set<String> values1 = new HashSet<>(map1.values());
    Set<String> values2 = new HashSet<>(map2.values());
    boolean equal = values1.equals(values2);
    

    It's possible that comparing map1.values() with map2.values() would work - but it's also possible that the order in which they're returned would be used in the equality comparison, which isn't what you want.

    Note that using a set has its own problems - because the above code would deem a map of {"a":"0", "b":"0"} and {"c":"0"} to be equal... the value sets are equal, after all.

    If you could provide a stricter definition of what you want, it'll be easier to make sure we give you the right answer.