Ive come across a nice problem recently, I have a Map
LinkedHashMap<String, List<MyCustomObject>>
I need to compare this to another Map, which will be populated in the exact same method is the data in the DB is the same.
What really is happening is , that I am populating map1 at time 0, and populating ma开发者_如何学运维p2 at time t, using the same java method(when I say this, i mean using the same DB/tables etc) So if the data on the DB side is same, then these two maps should have the same content, in the same order(hopefully!!)
Now I want to compare these two maps and if they are not equal (i.e some new data was fetched from the DB), then I want to do some action.If they are the same, I just want to leave it like that.
Can someone point me out to tutes that will help me understand how to do that??
Is serialization an answer to this??
Thanks, Neeraj
just use equals
:
if (!map1.equals(map2)) {
//they differ
}
you will have to implement equals
(and hashCode
!) on MyCustomObject
, since (if I understand correctly) the objects will have the same content but different identity (the default equals
just compares the pointers - i.e., the memory address in which the object live in).
Make sure that your MyCustomObject
class implements an appropriate equals
and hashcode
methods and then it's as easy as getting the result of map1.equals(map2)
.
This is what the javadocs have to say about it:
Compares the specified object with this map for equality. Returns true if the given object is also a map and the two Maps represent the same mappings. More formally, two maps t1 and t2 represent the same mappings if t1.entrySet().equals(t2.entrySet()). This ensures that the equals method works properly across different implementations of the Map interface.
The other answers are good and here's an illustration that indeed, the map functions iterate through the keys and the values (and compare items from the lists) to do equality comparison. As they say, you're going to need to override hashCode and equals.
static public List<String> getStringList(String... arg) {
ArrayList<String> arrayList = new ArrayList<String>();
for(int x=0;x<arg.length;x++) arrayList.add(arg[x]);
return arrayList;
}
static public void main(String[] arg) {
LinkedHashMap<String, List<String>> mapA = new LinkedHashMap<String, List<String>>();
LinkedHashMap<String, List<String>> mapB = new LinkedHashMap<String, List<String>>();
LinkedHashMap<String, List<String>> mapC = new LinkedHashMap<String, List<String>>();
mapA.put("same", getStringList("a", "b", "c"));
mapB.put("same", getStringList("a", "b", "c"));
mapC.put("same", getStringList("a", "b", "d"));
System.out.println(mapA.equals(mapB) ? "true" : "false");
System.out.println(mapA.equals(mapC) ? "true" : "false");
}
精彩评论