Approach :
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); } }
{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}
Australia
UK
UAE
Singapore
Canada
New
Zealand
Malaysia
USA
India
South
Africa
Ireland
Saudi
Arab
Qatar
Kuwait
Hongkong
Copyright 2016-2023 www.programmingshark.com - All Rights Reserved.
Disclaimer : Any type of help and guidance service given by us is just for reference purpose. We never ask any of our clients to submit our solution guide as it is, anywhere.