This is the second solution to identify the duplicate words in a given input sentence of strings, using the HashMap methods.
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Scanner;
import java.util.StringTokenizer;
public class DuplicatewordsUsingHashmap {
public static void main(String args[]) {
HashMap<String, Integer> wordsCnt = new HashMap<String, Integer>();
Scanner inpStr = new Scanner(System.in);
System.out.println("Enter an input sentence");
String sentence = inpStr.nextLine();
StringTokenizer words = new StringTokenizer(sentence);
//Storing the each word of given sentence into the HashMap
while (words.hasMoreTokens()) {
String nextWord=words.nextToken();
if(!wordsCnt.containsKey(nextWord))
wordsCnt.put(nextWord, 1);
else
wordsCnt.put(nextWord, wordsCnt.get(nextWord)+1);
}
System.out.println("The words HashMap below from the given input sentence");
System.out.println(wordsCnt);
//Traversing the wordsCnt HashMap to check the occurrences of any word entry more than one time
for(Entry<String, Integer> mapEntries: wordsCnt.entrySet()) {
if (mapEntries.getValue() > 1)
System.out.println("The word="+mapEntries.getKey()+" is repeated "+mapEntries.getValue()+" times");
}
inpStr.close();
}
}
Enter an input sentence
This example shows that This example, This example repeated
The words HashMap below from the given input sentence
{that=1, shows=1, This=3, repeated=1, example=2, example,=1}
The word=This is repeated 3 times
The word=example is repeated 2 times

Leave a comment