gpt4 book ai didi

java - 按 Stream API 的频率对集合进行排序

转载 作者:行者123 更新时间:2023-12-02 12:58:36 27 4
gpt4 key购买 nike

大家好,使用流的人,有这样一个问题。我有一张工作表,我想按其中字符出现的频率进行排序:

List<String> frequency = new ArrayList<>();
Collections.addAll(frequency, "gg", "ss", "gg", "boy", "girls", "girls", "gg", "boy", "aa", "aa");

我写了这个方法:

return words.stream().limit(limit).map(String::toLowerCase)
.collect(Collectors.groupingBy(Function.identity(),Collectors.counting()))
.entrySet().stream()
.map(entry -> new Pair<>(entry.getKey(), entry.getValue()))
.collect(Collectors.toList());

但是已经显示的答案不正确,字符串a完全丢失,字符串gg是一个元素,boys是一个元素

ss=1
gg=2
girls=2
boy=1

而且我不知道如何按出现频率对它们进行排序。结果应该是这样的:

gg=3
aa=2
boy=2
girls=2
ss=1

如何改进?

最佳答案

你可以这样做,

Map<String, Long> wordCount = frequency.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()))
.entrySet().stream()
.sorted(Map.Entry.<String, Long>comparingByValue(Comparator.reverseOrder())
.thenComparing(Map.Entry.comparingByKey()))
.collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue,
(e1, e2) -> e2, LinkedHashMap::new));

输出:{gg=3, aa=2, boy=2, girls=2, ss=1}

请注意,此处未使用 mergeFunction,因为不存在键冲突。

关于java - 按 Stream API 的频率对集合进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54285230/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com