Lets find the frequency of words in a sentence

This a quick tutorial for finding the frequency of each word in given string using java. This is a frequently asked question in interviews.

They might ask to write the code in Java or Java 8.

Lets see how to write it in Java 8 way first as Java 8 is trending in current market.

Java 8 way of doing it

String  input  = "Weather is good for living here";
 Map<String, Long> frequencyOfWords = Arrays.stream(input.split(" ")).collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

Not using Java 8

String input = "Weather is good for living here";
Map<String , Integer> frequencyOfWords = new HashMap<>();

for( String word : input.split(" ")){
if( frequencyOfWords.containsKey(word) ){
frequencyOfWords.put(word, frequencyOfWords.get(word) + 1);
} else { frequencyOfWords.put(word, 1);
}
}

 

Try the above codes and see the result.

Thanks for reading!!!!