Java Program to Find the Occurrence of Words in a String using HashMap
Last Updated :
19 Dec, 2021
HashMap<Key, Value> provides the basic implementation of the Map interface of Java and import java.util.HashMap package or its superclass. HashMap stores the data in (Key, Value) pairs, and accessed by an index of another type (e.g. an Integer). One object is used as a key to another object. If the duplicate key is inserted, it will replace the element of the corresponding key.
Approach :
- Declare a HashMap in Java of <String, Integer>
- Split the given string and store the words into a String array.
- Traversing the array, check if the word is in the HashMap or not.
- If it is not in the HashMap, then store the word as key and 1 as the initial value; if the word is present in the HashMap then increase the value against the word.
- Once the traversal is complete, print the HashMap.
Example:
Java
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) {
Integer integer = hashMap.get(word);
if (integer == null )
hashMap.put(word, 1 );
else {
hashMap.put(word, integer + 1 );
}
}
System.out.println(hashMap);
}
}
|
Output
{Bob=1, Alice=1, and=1, is=2, girl=1, boy=1}
Note that in the above code, we have 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
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) {
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}
Share your thoughts in the comments
Please Login to comment...