Home >Java >javaTutorial >How to Calculate Word Frequencies in a List Using Java 8?

How to Calculate Word Frequencies in a List Using Java 8?

DDD
DDDOriginal
2024-10-30 02:11:29755browse

How to Calculate Word Frequencies in a List Using Java 8?

Word frequency counting in Java 8

How to count the frequency of a word in a list using Java 8?

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

The result should be:

<code class="java">{ciao=2, hello=1, bye=2}</code>

At first, I expected to use the map and reduce method, but the actual method is slightly different.

<code class="java">Map<String, Long> collect = wordsList.stream()
    .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));</code>

Or for integer values:

<code class="java">Map<String, Integer> collect = wordsList.stream()
     .collect(Collectors.groupingBy(Function.identity(), Collectors.summingInt(e -> 1)));</code>

EDIT

I also added how to sort the map by value:

<code class="java">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
            ));</code>

The above is the detailed content of How to Calculate Word Frequencies in a List Using Java 8?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn