Map集合排序

public static void main(String[] args) {
//这里自定义一个需要排序的map集合
Map<String, Integer> map = new HashMap<String, Integer>();
map.put("1.B.1.c", 45);
map.put("1.B.1.d", 65);
map.put("1.B.1.a", 12);
map.put("1.B.1.b", 15);
map.put("1.B.1.e", 78);
int size = map.size();
// 通过map.entrySet()将map转换为"1.B.1.e=78"形式的list集合
List<Map.Entry<String, Integer>> list = new ArrayList<Map.Entry<String, Integer>>(size);
list.addAll(map.entrySet());
// 通过Collections.sort()排序
Collections.sort(list, new Comparator<Map.Entry<String, Integer>>() {
public int compare(Map.Entry<String, Integer> o1, Map.Entry<String, Integer> o2) {
// compareTo方法 (x < y) ? -1 : ((x == y) ? 0 : 1)
return o1.getValue().compareTo(o2.getValue());
};
});
for (Entry<String, Integer> entry : list){
// 得到排序后的键值
System.out.println(entry.getKey());
}
}
原文地址:https://www.cnblogs.com/think-world/p/12392748.html