How to find out the occurrence of words in a string using HashMap in java

Approach :

  • Declare a HashMap in Java of
  • Split the given string and store the words into a String array.
  • Traversing the array, check if the word is within the HashMap or not.
  • If it's not within the HashMap, then store the word as key and 1 because the initial value; if the word is present within the HashMap then increase the worth against the word.
  • Once the traversal is complete, print the HashMap.

Example:

 
// Java Program to find the occurrence
// of words in a String using HashMap.
import java.io.*;
import java.util.HashMap;
import java.util.Map;

class GFG {
	public static void main(String[] args)
	{

		// Declaring the String
		String str = "Alice is girl and Bob is boy";
		// Declaring a HashMap of <String, Integer>
		Map<String, Integer> hashMap = new HashMap<>();

		// Spliiting the words of string
		// and storing them in the array.
		String[] words = str.split(" ");

		for (String word : words) {

			// Asking whether the HashMap contains the
			// key or not. Will return null if not.
			Integer integer = hashMap.get(word);

			if (integer == null)
				// Storing the word as key and its
				// occrence as value in the HashMap.
				hashMap.put(word, 1);

			else {
				// Incrementing the value if the word
				// is already present in the HashMap.
				hashMap.put(word, integer + 1);
			}
		}
		System.out.println(hashMap);
	}
}
Output
{Bob=1, Alice=1, and=1, is=2, girl=1, boy=1}

Note that within the above code, we've used Wrapper class i.e. Integer, since the get(key) method returns null.

You can also eliminate the use of integer variable from the above program.

Let us see the code below :

// Java Program to find the occurrence
// of words in a String using HashMap.
import java.io.*;
import java.util.HashMap;
import java.util.Map;

class GFG {
	public static void main(String[] args)
	{

		String str = "Alice is girl and Bob is boy";

		Map<String, Integer> hashMap = new HashMap<>();

		String[] words = str.split(" ");

		for (String word : words) {
			// containsKey(key) will return a boolean value
			// i.e. true if it contains the key and false if
			// it doesn't.
			if (hashMap.containsKey(word))
				hashMap.put(word, hashMap.get(word) + 1);

			else
				hashMap.put(word, 1);
		}

		System.out.println(hashMap);
	}
}

Output

{Bob=1, Alice=1, and=1, is=2, girl=1, boy=1}

 

Submit Your Programming Assignment Details