Map<String, Integer> map = new HashMap<>();
map.put("zs", 80);
map.put("ls", 75);
map.put("wz", 81);
map.put("zl", 77);
//需要有序的map对结果进行收集
Map<String, Integer> map2 = new LinkedHashMap<>();
//1、使用stream流
map.entrySet().stream().sorted((o1, o2) -> o1.getValue() - o2.getValue()).
forEach(e -> map2.put(e.getKey(), e.getValue()));
// {ls=75, zl=77, zs=80, wz=81}
System.out.println(map2);
//2、将map转换为list,对list进行排序,同样放入LinkedHashMap
ArrayList<Map.Entry<String, Integer>> entries = new ArrayList<>(map.entrySet());
Collections.sort(entries, (o1, o2) -> o1.getValue() - o2.getValue());
Map<String, Integer> map3 = new LinkedHashMap<>();
entries.forEach(e -> map3.put(e.getKey(), e.getValue()));
// {ls=75, zl=77, zs=80, wz=81}
System.out.println(map3);
Java中根据map的value对map进行排序
于 2022-08-15 15:46:28 首次发布