按值和键的降序对以下内容进行排序。我修改了列表以使其更有趣。
Map<String, Integer> map = Map.of("a", 8, "b", 2, "c", 4, "d",
8, "e", 3, "f", 4, "g", 7, "h", 1, "i", 5, "j", 2);
首先定义一个Comparator 用于对Map 条目进行排序。每个条目都由Map.Entry 类表示。该类提供方法comparingByValue() 和comparingByKey()。
下面的代码说,首先按value 排序,然后按key。这些按自然顺序排序,但以下reversed() 方法表示反转所有比较器的排序。因此values 将按相反顺序排序,keys 按字母顺序排序。
Comparator<Entry<String, Integer>> comp = Entry
.<String, Integer>comparingByValue().reversed()
.thenComparing(Entry.comparingByKey());
这会流式传输现有地图的条目并将比较器应用于排序方法。然后它将它们收集在链接的 hashMap 中以保留顺序。合并函数在其中没有作用,但在语法上是必需的。
Map<String, Integer> lhmap =
map.entrySet().stream().sorted(comp)
.collect(Collectors.toMap(Entry::getKey,
Entry::getValue,
(a, b) -> a, // merge function
LinkedHashMap::new));
lhmap.entrySet().forEach(System.out::println);
该代码打印:
a=8
d=8
g=7
i=5
c=4
f=4
e=3
b=2
j=2
h=1