@Test
public void test2() {
HashMap<String, Integer> scoreMap = new HashMap<>();
LinkedHashMap<String, Integer> scoreDescMap = new LinkedHashMap<>();
LinkedHashMap<String, Integer> scoreAscMap = new LinkedHashMap<>();
scoreMap.put("语文", 101);
scoreMap.put("数学", 99);
scoreMap.put("英语", 102);
scoreMap.put("理综", 221);
// Map 根据 Value排序
System.out.println("------从低到高----------");
scoreMap.entrySet().stream().sorted((o1, o2) -> (o1.getValue() - o2.getValue()))
.forEach(e -> scoreDescMap.put(e.getKey(), e.getValue()));
for (Map.Entry<String, Integer> entry : scoreDescMap.entrySet()) {
System.out.println(entry);
}
System.out.println("------从高到低----------");
scoreMap.entrySet().stream().sorted((o1, o2) -> -((o1.getValue() - o2.getValue())))
.forEach(e -> scoreAscMap.put(e.getKey(), e.getValue()));
for (Map.Entry<String, Integer> entry : scoreAscMap.entrySet()) {
System.out.println(entry);
}
}
Map根据Value排序--Java
最新推荐文章于 2024-06-06 11:24:10 发布