我能够像Boris的建议答案一样完成这个任务。然而,我使用的任何IDE都拒绝推断泛型类型,因此我必须在第一次调用Comparator#comparing
时明确指定它们,如下所示:
Map<String, Integer> map = new LinkedHashMap<>();
map.put("garden", 2);
map.put("road", 4);
map.put("street", 5);
map.put("park", 5);
map.put("highway", 5);
map = map.entrySet()
.stream()
.sorted(Comparator.<Entry<String, Integer>, Integer>comparing(Entry::getValue)
.thenComparing(Comparator.comparing(Entry::getKey)))
.collect(Collectors.toMap(Entry::getKey, Entry::getValue, (k, v) -> {
throw new IllegalStateException(String.format("Duplicate Key: %s", k));
}, LinkedHashMap::new));
System.out.println(map);
上面的代码产生以下输出:
{garden=2,road=4,highway=5,park=5,street=5}
我注意到您希望值按降序排列,但共享值的键按升序排列。以下是几乎相同的解决方案:
map = map.entrySet()
.stream()
.sorted(Comparator.<Entry<String, Integer>, Integer>comparing(Map.Entry::getValue).reversed()
.thenComparing(Comparator.comparing(Entry::getKey)))
.collect(Collectors.toMap(Entry::getKey, Entry::getValue, (k, v) -> {
throw new IllegalStateException(String.format("Duplicate key %s", k));
}, LinkedHashMap::new));
注意: Entry
是指 java.util.Map.Entry
,Collectors
是指 java.util.stream.Collectors
。
data.entrySet().stream().sorted(Comparator.comparing(Entry::getValue).thenComparing(Comparator.comparing(Entry::getKey))).collect(Collectors.toMap(Entry::getKey, Entry::getValue, mergeFunction, LinkedHashMap::new))
。 - Boris the Spider