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
Release: 2024-10-30 02:11:29
Original
726 people have browsed it

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>
Copy after login

The result should be:

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

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>
Copy after login

Or for integer values:

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

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template