日期:2014-05-17  浏览次数:20719 次

关于比较Map对象问题
现在我们需要把两个Map对象的键值进行对比,例如
Map<String,String> m1 = new HashMap<String,String>(); 
Map<String,String> m2 = new HashMap<String,String>(); 

m1.put("1", "tom");
m1.put("2", "我");
m1.put("3", "jack");

m2.put("4", "jack");
m2.put("2", "我");
m2.put("3", "tom");
我们需要先把键对比,当键相同的时候再比较值,谁知道怎么对比?请帮帮忙,谢谢各位了!

------解决方案--------------------
Map<String,String> m1 = new HashMap<String,String>();
Map<String,String> m2 = new HashMap<String,String>();

m1.put("1", "tom");
m1.put("2", "我");
m1.put("3", "jack");

m2.put("4", "jack");
m2.put("2", "我");
m2.put("3", "tom");

Set<String> keySet = m1.keySet();
Iterator<String> it = keySet.iterator();
String key = null;
while(it.hasNext()){
key = it.next();
if(m1.get(key).equals(m2.get(key))){
System.out.println("m1中的'" + key + "'和m2中的相等");
}
}