user2958542
user2958542

Reputation: 341

Iterate through two TreeMaps to compare in Java

At first I had something like this:

public static boolean equals(TreeMap<?, Boolean> a, TreeMap<?, Boolean> b) {
    boolean isEqual = false;
    int count = 0;
    if (a.size() == b.size()) {
        for (boolean value1 : a.values()) {
            for (boolean value2 : b.values()) {
                if (value2 == value1) {
                    count++;
                    isEqual = true;
                    continue;
                } else {
                    isEqual = false;
                    return isEqual;
                }
            }
        }
        if (count == a.size()) {
            return true;
        }
    }
}

Then found that nope it didn't work. I'm checking to see if every element in Object a is the same as in Object b without using Iterate or Collection. and in the same place... any suggestions? Would implementing a for-each loop over the keySet() work?

So, something along these lines? Needing to take in account BOTH keys and values: (Not an answer - test code for suggestions)

Upvotes: 1

Views: 3869

Answers (3)

Andrey Chaschev
Andrey Chaschev

Reputation: 16476

This should work as values() are backed up by the TreeMap, so are sorted according to the key values.

List<Boolean> aList = new ArrayList<>(a.values());
List<Boolean> bList = new ArrayList<>(b.values());

boolean equal = aList.equals(bList);

This should be a bit faster than a HashSet version.

And this won't work as @AdrianPronk noticed:

a.values().equals(b.values())

Upvotes: 4

user1556613
user1556613

Reputation:

For Comparing two Map Objects in java, you can add the keys of a map to list and with those 2 lists you can use the methods retainAll() and removeAll() and add them to another common keys list and different keys list.

The correct way to compare maps 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

Upvotes: 0

Anuj Kulkarni
Anuj Kulkarni

Reputation: 2199

How about this :

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

Upvotes: 2

Related Questions