Count the number of word in a string using HashMap in java 8
Program to Count the number of word in a string using HashMap in java 8, we are using following approach.
- Take a String array input data.
- First convert Arrays to list using Arrays.asList method.
- Now, get Stream data from List using arrayList.stream() method.
- Inside Collect(collectors.groupingBy(Function.identity(),collectors.counting())) method, that uses streams to count the occurrences of each element in a collection. here Function.identity(), we group the elements of a stream based on their own value.
- Also, collectors.counting() method counts the number of elements in each group.
- Print Occurrence of Words in a String using HashMap.
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<String, Long> count = Arrays.asList(str).stream() .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
System.out.println("word count are :- " + count);
}
}
Output :-
word count are :- {spring=2, java=2, jsp=1, hibernate=1}
Count the number of word in a string using HashMap in java 8 Read More »