java中Map按value排序
Map<String, Integer> map1 = new HashMap<>();
map1.put("abc1", 5);
map1.put("abc2", 3);
map1.put("abc3", 20);
map1.put("abc4", 80);
map1.put("abc5", 1);
map1.put("abc6", 10);
map1.put("abc7", 12);
List<Map.Entry<String,Integer>> list = new ArrayList<>(map1.entrySet()); //将Map转换成List
Collections.sort(list, (o1, o2) -> o1.getValue() - o2.getValue()); // 借助List的sort方法,需要重写排序规则
// (list, (::getValue)); // IDE 提示可以写成更简便的这种形式,我还是习惯自己重新,然后lambda简化
Map<String, Integer> map2 = new LinkedHashMap<>(); // 这里必须声明成为LinkedHashMap,否则构造新map时会打乱顺序
for(Map.Entry<String, Integer> o:list){ // 构造新map
map2.put(o.getKey(),o.getValue());
}
for(Map.Entry<String,Integer> entry:map2.entrySet()){ // out
System.out.println(entry.getValue());
}