词频计数 Java 8

2022-01-22 00:00:00 word-count java-8 java java-stream

Java 8中如何统计List的词频?

How to count the frequency of words of List in Java 8?

List <String> wordsList = Lists.newArrayList("hello", "bye", "ciao", "bye", "ciao");

结果必须是:

{ciao=2, hello=1, bye=2}

推荐答案

我想分享我找到的解决方案,因为一开始我希望使用 map-and-reduce 方法,但它有点不同.

I want to share the solution I found because at first I expected to use map-and-reduce methods, but it was a bit different.

Map<String, Long> collect = 
        wordsList.stream().collect(groupingBy(Function.identity(), counting()));

或者对于整数值:

Map<String, Integer> collect = 
        wordsList.stream().collect(groupingBy(Function.identity(), summingInt(e -> 1)));

编辑

我添加了如何按值对地图进行排序:

I add how to sort the map by value:

LinkedHashMap<String, Long> countByWordSorted = collect.entrySet()
            .stream()
            .sorted(Map.Entry.comparingByValue(Comparator.reverseOrder()))
            .collect(Collectors.toMap(
                    Map.Entry::getKey,
                    Map.Entry::getValue,
                    (v1, v2) -> {
                        throw new IllegalStateException();
                    },
                    LinkedHashMap::new
            ));

相关文章