import java.util.HashMap; import java.util.Set; public class DuplicateWordsExample { public void findDuplicateWord(String stringAsInput) { String[] wordsAsArray = stringAsInput.split(" "); HashMap<String, Integer> wordMap = new HashMap<String, Integer>(); for (String wordString : wordsAsArray) { if (wordMap.containsKey(wordString)) { wordMap.put(wordString, wordMap.get(wordString) + 1); } else { wordMap.put(wordString, 1); } } Set<String> wordsAsString = wordMap.keySet(); for (String wordStr : wordsAsString) { if (wordMap.get(wordStr) > 1) { System.out.println(wordStr + " : " + wordMap.get(wordStr)); } } } public static void main(String[] args) { DuplicateWordsExample duplicateWordsExample = new DuplicateWordsExample(); duplicateWordsExample.findDuplicateWord("ram is is good good boy"); } }
Output is –
is : 2
good : 2