Home  >  Article  >  Java  >  How to Count Word Occurrences in a List using `groupBy` and `Collectors.counting()` in Java?

How to Count Word Occurrences in a List using `groupBy` and `Collectors.counting()` in Java?

Linda Hamilton
Linda HamiltonOriginal
2024-11-17 20:56:02385browse

How to Count Word Occurrences in a List using `groupBy` and `Collectors.counting()` in Java?

Counting Occurrences Using groupBy

One technique for categorizing and summarizing data in a stream is to utilize the groupBy method. By leveraging groupBy, we can segregate elements based on their characteristics and conduct operations on the resulting groups.

In your particular scenario, you seek to ascertain the frequency of words in a given list. One efficient approach is to combine groupBy with Collectors.counting(). This technique enables you to group objects with similar attributes and determine the number of occurrences within each group.

For instance, given the input list:

List<String> list = Arrays.asList("Hello", "Hello", "World");

You can retrieve a map with the word count as follows:

import java.util.*;
import java.util.stream.*;

class Test {
    public static void main(String[] args) {
        Map<String, Long> wordToFrequency = list.stream()
            .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

        System.out.println(wordToFrequency);
    }
}

The resulting map will be:

{Hello=2, World=1}

Where each key represents a unique word, and its corresponding value denotes its appearance count within the list.

The above is the detailed content of How to Count Word Occurrences in a List using `groupBy` and `Collectors.counting()` in Java?. 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