您不能按地图的值对地图进行排序。我认为你能做到的最好的是将排序的条目存储到 LinkedHashMap 中,这样当你迭代其他条目时,你会得到预期的结果(因为你会按所需的排序顺序添加映射)。
为此,您需要第一个按操作分组,以了解如何构建映射“字母 -> 出现次数”(您也可以考虑使用 Map<Character, Long>)。
然后您必须再次遍历条目集,并对流进行排序,以便条目首先按其值排序,然后按键的自然顺序排序。所以比较器看起来像:
//need to provide explicit type parameters due to limited type inference at the moment
Comparator<Map.Entry<String, Long>> cmp =
Map.Entry.<String, Long>comparingByValue(reverseOrder()).thenComparing(Map.Entry.comparingByKey());
将所有部分放在一起,结果是:
Map<String, Long> letters =
fruits.flatMap(w -> Arrays.stream(w.split("")))
.collect(groupingBy(identity(), counting()))
.entrySet()
.stream()
.sorted(Map.Entry.<String, Long>comparingByValue(reverseOrder()).thenComparing(Map.Entry.comparingByKey()))
.collect(toMap(Map.Entry::getKey, Map.Entry::getValue, (a, b) -> {throw new IllegalStateException();}, LinkedHashMap::new));
产生:
{a=5, n=3, e=2, p=2, g=1, l=1, o=1, r=1, s=1}