根据值降序对Map进行排序,如果值重复则按升序对键进行排序
Sorting the Map in descending order based on the value and sort the key in ascending order if value is duplicate
我正在使用映射接口从文件中读取,然后将值作为键值对存储在其中。
Map<String, Integer> map = new HashMap<>();
值为
A 25
D 10
B 15
E 15
C 17
我想先按值降序排列Sorting the Map<Key,Value> in descending order based on the value 。这将有助于实现降序排列。但如果值重复,我想按升序按键排序。
预期输出
A 25
C 17
B 15
E 15
D 10
有谁知道如何做到这一点。
您可以使用 Comparator.comparing
和 thenComparing
以正确的顺序排序。可以使用 Streams 将新的 Map
排序并收集到一个 LinkedHashMap
以保留新的顺序。
Map<String, Integer> map = Map.of("A", 25, "D", 10, "B", 15, "E", 15, "C", 17);
Map<String, Integer> result = map.entrySet().stream()
.sorted(Comparator.<Map.Entry<String, Integer>>comparingInt(Map.Entry::getValue)
.reversed().thenComparing(Map.Entry::getKey))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
(a,b)->b, LinkedHashMap::new));
System.out.println(result);
作为已接受答案的替代方案,我将提取 IMO 使其更具可读性的比较器,即类似于:
Map<String, Integer> map = Map.of("A", 25, "D", 10, "B", 15, "E", 15, "C", 17);
Comparator<Map.Entry<String,Integer>> byValueDesc = Map.Entry.comparingByValue(Comparator.reverseOrder());
Comparator<Map.Entry<String,Integer>> byKeyAsc = Map.Entry.comparingByKey();
Map<String, Integer> result =
map.entrySet()
.stream()
.sorted(byValueDesc.thenComparing(byKeyAsc))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1,e2)->e1, LinkedHashMap::new));
我正在使用映射接口从文件中读取,然后将值作为键值对存储在其中。
Map<String, Integer> map = new HashMap<>();
值为
A 25
D 10
B 15
E 15
C 17
我想先按值降序排列Sorting the Map<Key,Value> in descending order based on the value 。这将有助于实现降序排列。但如果值重复,我想按升序按键排序。
预期输出
A 25
C 17
B 15
E 15
D 10
有谁知道如何做到这一点。
您可以使用 Comparator.comparing
和 thenComparing
以正确的顺序排序。可以使用 Streams 将新的 Map
排序并收集到一个 LinkedHashMap
以保留新的顺序。
Map<String, Integer> map = Map.of("A", 25, "D", 10, "B", 15, "E", 15, "C", 17);
Map<String, Integer> result = map.entrySet().stream()
.sorted(Comparator.<Map.Entry<String, Integer>>comparingInt(Map.Entry::getValue)
.reversed().thenComparing(Map.Entry::getKey))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
(a,b)->b, LinkedHashMap::new));
System.out.println(result);
作为已接受答案的替代方案,我将提取 IMO 使其更具可读性的比较器,即类似于:
Map<String, Integer> map = Map.of("A", 25, "D", 10, "B", 15, "E", 15, "C", 17);
Comparator<Map.Entry<String,Integer>> byValueDesc = Map.Entry.comparingByValue(Comparator.reverseOrder());
Comparator<Map.Entry<String,Integer>> byKeyAsc = Map.Entry.comparingByKey();
Map<String, Integer> result =
map.entrySet()
.stream()
.sorted(byValueDesc.thenComparing(byKeyAsc))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1,e2)->e1, LinkedHashMap::new));