There are following way to find the duplicate words in a string.
- First we break the String from split() method and return string array.
- Now create HashMap object to count word and there number of times word.
- Create for loop to iterate String array into String.
- Now check word as key store in HashMap from containsKey() method
- Here word take as key and from get() method to pass word find value.
- Create Set class to find total key from keySet() method.
- Inside if condition check string value is greater than one or not.
- Now print the result.
import java.util.HashMap;
import java.util.Set;
public class CountDuplicateWord {
public static void main(String[] args) {
String h = "java spring java";
String[] words = h.split(" ");
HashMap wordcount = new HashMap();
for (String word : words) {
if (wordcount.containsKey(word)) {
wordcount.put(word, wordcount.get(word) + 1);
} else {
wordcount.put(word, 1);
}
}
Set k = wordcount.keySet();
for (String str : k) {
if (wordcount.get(str) > 1) {
System.out.println("word name :- "+str+ " ,number of times word is :-"+wordcount.get(str));
}
}
System.out.println("Total word and times of count :- " + wordcount);
}
}
Output :-
word name :- java ,number of times word is :-2
Total word and times of count :- {spring=1, java=2}