public static void main(String[] args) {
// 创建一个Map
Map<String, Integer> map = new HashMap<>();
map.put("小明", 1);
map.put("小红", 3);
map.put("张三", 2);
map.put("李四", 4);
// 正序配列
List<Map.Entry<String, Integer>> sortedMapOne = mapValueAsc(map);
for (Map.Entry<String, Integer> entry : sortedMapOne) {
System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
}
System.out.println("-----------------------------------------------------");
// 倒叙排列
List<Map.Entry<String, Integer>> sortedMapTwo = mapValueDesc(map);
// 打印排序后的Map
for (Map.Entry<String, Integer> entry : sortedMapTwo) {
System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
}
}
// 根据value值正叙排列
public static List<Map.Entry<String, Integer>> mapValueAsc(Map<String,Integer> map){
return map.entrySet().stream().sorted(Map.Entry.comparingByValue()).collect(Collectors.toList());
}
// 根据value值倒叙排列
public static List<Map.Entry<String, Integer>> mapValueDesc(Map<String,Integer> map){
return map.entrySet().stream().sorted(Map.Entry.<String,Integer>comparingByValue().reversed()).collect(Collectors.toList());
}