在刷题和业务编码的过程中有时会有对map按值进行排序的需求。总结了两种方法,它们都需要生成一个新的map作为返回:
方法一:借助List进行排序
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方法,需要重写排序规则
// Collections.sort(list, Comparator.comparingInt(Map.Entry::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());
}
方法二:借助stream进行排序
Map<String, Integer> sorted = map1
.entrySet()
.stream()
.sorted(comparingByValue())
.collect(
toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e2,
LinkedHashMap::new));
// 这种方式在Leetcode上不能用,方法找不到