Posts

Showing posts with the label Find Frequency of each Word in a String

Java Program to Find Frequency of each Word in a String

Image
In this section, we will show you three different ways to find frequency of each word in a given String in Java. 1.  Using For loop and Map  2. Using Java 8 Streams 3. Using Google Guava MultiSet Example 1: Using For loop and Map  import java.util.HashMap ; import java.util.Map ; public class Main { public static void main ( String [] args) { String string = "Java Python Go C# Java Python Java Go C" ; //Split the string into words based on whitespace String words [] = string .split( " " ); Map < String , Integer > occurrences = new HashMap<>(); //Iterate through String array for ( String word : words ) { Integer oldCount = occurrences .get( word ); if ( oldCount == null ) { oldCount = 0 ; } occurrences .put( word , oldCount + 1 ); } System . out .println( occurrences ); } } 1.  split() method in Java splits a string in