Compare Maps – Java

One of my today’s subtasks  was to compare 2 maps instances. I found the Apache Commons’s CollectionUtils which is a useful and smart class ( but needless for my aim).  So I didn’t find some satisfactory solution in Internet and I write ( and test :)) my own implementation. Unfortunately the example below is a non-Generic code ( because in my new job we use under Java 5 ), so excuse me for that.

package comparator;
import java.util.Iterator;
import java.util.Map;

public class MapComparator {

	public static boolean compareMaps(Map map1, Map map2) {
		if (map1 == null && map2 == null) {
			return true;
		}
		if ((map1 == null && map2 != null) || (map1 != null && map2 == null)) {
			return false;
		}
		if (map1.size() != map2.size()) {
			return false;
		}
		Iterator iterator = map1.entrySet().iterator();
		while (iterator.hasNext()) {
			Map.Entry mapEntry = (Map.Entry) iterator.next();
			Object map1key = mapEntry.getKey();
			Object map1value = mapEntry.getValue();

			if (map2.containsKey(map1key)) {
				Object map2value = map2.get(map1key);
				if ((map1value.equals(map2value))) {
					continue;
				} else {
					return false;
				}
			} else {
				return false;
			}
		}
		return true;
	}
}

Just to remind you that you should override equals() method in the class of Map’s value. Otherwise, the comparison

map1value.equals(map2value)

is legal but useless.

P.S. About iteration over Map Interface these 2 links were very useful for me:  Official Java Tutorial website and Mkyong’s website.

Advertisements

About tsvetanv

Friends, Books, Music, Math, Programming.
This entry was posted in Java and tagged . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s