Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 707
paweloque Avatar asked Apr 20 '10 09:04

paweloque


People also ask

How do you compare two Hashmaps by their keys?

If we want to compare hashmaps by keys i.e. two hashmaps will be equals if they have exactly same set of keys, we can use HashMap. keySet() function. It returns all the map keys in HashSet. We can compare the hashset of keys for both maps using Set.

Can a Map have 2 values?

The Map interface stores the elements as key-value pairs. It does not allow duplicate keys but allows duplicate values. HashMap and LinkedHashMap classes are the widely used implementations of the Map interface. But the limitation of the Map interface is that multiple values cannot be stored against a single key.

How do you find the value of a Map?

HashMap. get() method of HashMap class is used to retrieve or fetch the value mapped by a particular key mentioned in the parameter. It returns NULL when the map contains no such mapping for the key.

How can I compare two maps in C++?

C++ Map Library - operator== Functionb The C++ function std::map::operator== tests whether two maps are equal or not.


1 Answers

The correct way to compare maps for value-equality is to:

  1. Check that the maps are the same size(!)
  2. Get the set of keys from one map
  3. For each key from that set you retrieved, check that the value retrieved from each map for that key is the same (if the key is absent from one map, that's a total failure of equality)

In other words (minus error handling):

boolean equalMaps(Map<K,V>m1, Map<K,V>m2) {
   if (m1.size() != m2.size())
      return false;
   for (K key: m1.keySet())
      if (!m1.get(key).equals(m2.get(key)))
         return false;
   return true;
}
like image 96
Donal Fellows Avatar answered Sep 19 '22 16:09

Donal Fellows