把Map中的数据按照value的大小进行排序并输出是一个比较常见的需求.
思路:
1)将map中的所有entry转化为一个ArrayList:
List<Map.Entry<String, Integer>> cityInfoList = new ArrayList<Map.Entry<String, Integer>>(cityInfo.entrySet());
2)调用Collections.sort()方法,对元素(Map entry)进行排序:
Collections.sort(cityInfoList, new Comparator<Map.Entry<String, Integer>>() {
@Override
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
return o2.getValue().compareTo(o1.getValue());
}
});
总结:
1)将map中的所有entry转化为一个ArrayList;
2)调用Collections.sort()方法,对元素(Map entry)进行排序,Comparator中自定义了按照map 中value进行排序.