I need to find repeated words on a string, and then count how many times they were repeated. So basically, if the input string is this:
String s = \"House, House
You've got the hard work done. Now you can just use a Map
to count the occurrences:
Map occurrences = new HashMap();
for ( String word : splitWords ) {
Integer oldCount = occurrences.get(word);
if ( oldCount == null ) {
oldCount = 0;
}
occurrences.put(word, oldCount + 1);
}
Using map.get(word)
will tell you many times a word occurred. You can construct a new list by iterating through map.keySet()
:
for ( String word : occurrences.keySet() ) {
//do something with word
}
Note that the order of what you get out of keySet
is arbitrary. If you need the words to be sorted by when they first appear in your input String, you should use a LinkedHashMap
instead.