Home >Java >javaTutorial >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!