Learn how to count word occurrences in Java 8 using HashMap , Streams, Collectors.groupingBy(), Function.identity(), and Collectors.counting() with example.
Code Explanation (Step-by-Step) :
- Create a string array that contains repeated words.
- Arrays.asList() converts array elements into a List.
- stream() creates a stream from the list.
- Use Collectors.groupingBy() to group words based on their value.
- Use Function.identity() to treat each word as its own grouping key.
- Use Collectors.counting() to count how many times each word appears.
- Store the result in a Map<String, Long>.
- Print the word occurrence count.
import java.util.Arrays;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
public class CountWords {
public static void main(String[] args) {
String[] str = { "java", "spring", "jsp", "java", "hibernate", "spring" };
Map count = Arrays.asList(str)
.stream()
.collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
System.out.println("Word count is: " + count);
}
}
Output :
Word count is: {spring=2, java=2, jsp=1, hibernate=1}
How to Count the Occurrence of a String in an Array of Strings
import java.util.HashMap;
import java.util.Map;
public class WordCountUsingMerge {
public static void main(String[] args) {
String[] str = { "java", "spring", "jsp", "java", "hibernate", "spring" };
Map wordCount = new HashMap<>();
for (String word : str) {
wordCount.merge(word, 1, Integer::sum);
}
System.out.println(wordCount);
}
}
Output :
Word count is: {spring=2, java=2, jsp=1, hibernate=1}
FAQ
How do you count word occurrences in Java 8?
You can count word occurrences in Java 8 by using Streams with Collectors.groupingBy() and Collectors.counting().
What does Function.identity() do in Java 8?
Function.identity() returns the same input value and is used here to group words by their own value.
Which collector is used to count words in Java 8?
Collectors.counting() is used to count the number of occurrences of each word.
Can we use HashMap to count duplicate words in Java?
Yes, we can use HashMap to store each word as a key and its occurrence count as the value.