Write a Java Program to count the number of words in a string using HashMap.
Answers
Answer:
Let’s write a program to count the word in a sentence using java HashMap an implementation class of Map.
Map is data structure which contains value based on key.
import java.util.*; // package contains the collection classes. ex Map, HashMap, TreeSet etc
class WordCount {
public static void main(String args[]) {
Map < String, Integer > map = new HashMap < > ();
Scanner sc = new Scanner(System.in); // used to read user input
System.out.println("Enter a string:");
String sentence = sc.nextLine();
String[] tokens = sentence.split(" "); // split based on space
for (String token: tokens) {
String word = token.toLowerCase();
if (map.containsKey(word)) {
int count = map.get(word); // get word count
map.put(word, count + 1); // override word count
} else {
map.put(word, 1); // initial word count to 1
}
}
//display the data
Set < String > keys = map.keySet(); // list of unique words because it's a Set
TreeSet < String > sortedKeys = new TreeSet < > (keys); // ascending order of words
for (String str: sortedKeys) {
System.out.println("Word =" + str + " and it's count = " + map.get(str));
}
}
}JavaCopy
Examples:
Input: str = "Ajit"
Output:
A 1
t 1
i 1
j 1
Below is the implementation of the above approach.
// Java prorgam to count frequencies of
// characters in string using Hashmap
import java.io.*;
import java.util.*;
class OccurenceOfCharInString {
static void characterCount(String inputString)
{
// Creating a HashMap containing char
// as a key and occurrences as a value
HashMap<Character, Integer> charCountMap
= new HashMap<Character, Integer>();
// Converting given string to char array
char[] strArray = inputString.toCharArray();
// checking each char of strArray
for (char c : strArray) {
if (charCountMap.containsKey(c)) {
// If char is present in charCountMap,
// incrementing it's count by 1
charCountMap.put(c, charCountMap.get(c) + 1);
}
else {
// If char is not present in charCountMap,
// putting this char to charCountMap with 1 as it's value
charCountMap.put(c, 1);
}
}
// Printing the charCountMap
for (Map.Entry entry : charCountMap.entrySet()) {
System.out.println(entry.getKey() + " " + entry.getValue());
}
}
// Driver Code
public static void main(String[] args)
{
String str = "Ajit";
characterCount(str);
}
}
Output:
A 1
t 1
i 1
j 1