Map<String, String> map1 = new HashMap<String, String>();
Map<String, String> map2 = new HashMap<String, String>();
比较两个Map中相同key中对应value
方法一:通过map.keySet()
方法
for(String key1 : map1.keySet()){
String map1value = map1.get(key1);
String map2value = map2.get(key1);
if (!map1value.equals(map2value)) {
...
}
}
方法二:通过map.keySet()
的迭代器
Iterator<String> iter1 = map1.keySet().iterator();
while(iter1.hasNext()){
String map1key=iter1.next();
String map1value = map1.get(map1key);
String map2value = map2.get(map1key);
if (!map1value.equals(map2value)) {
...
}
}
方法三:通过map.entrySet()
的增强型for循环
for(Entry<String, String> entry1 : map1.entrySet()){
String m1value = entry1.getValue() == null?"":entry1.getValue();
String m2value = m2.get(entry1.getKey())==null?"":m2.get(entry1.getKey());
if (!m1value.equals(m2value)) {
...
}
}
方法四:用map.entrySet()
迭代器
Iterator<Entry<String,String>> iter1 = map1.entrySet().iterator();
while(iter1.hasNext()){
Entry<String,String> entry1 = iter.next();
//获取key与value
//String key = entry.getKey();
//String value = entry.getValue();
String m1value = entry1.getValue() == null?"":entry1.getValue();
String m2value = m2.get(entry1.getKey())==null?"":m2.get(entry1.getKey());
if (!m1value.equals(m2value)) {
...
}
}
对Map中元素进行排序
List<Entry<String,String>> list = new ArrayList<Entry<String,String>>(map.entrySet());
Collections.sort(list,new Comparator<Entry<String,String>>(){
@Override
public int compare(Entry<String, String> o1, Entry<String, String> o2) {
int flag = o1.getValue().compareTo(o2.getValue());
if(flag==0)
return o1.getKey().compareTo(o2.getKey());
return flag;
}
});