My program contains algorithms that output text (String). Eventually I want to print out the word that occurred the most. But before I do this, I need to store it in a data structure. So I was wondering what data structure is the best (easy and efficient) to store Strings and then be able to obtain the most frequent element? I don't want to use any libraries. Thanks
I don't think any data structure does exactly this but here is how I would do it.
Maintain a Map<String, Integer> of each word to the number of times it was encountered and as you update the map keep track of the string corresponding to the largest number stored. For example:
String maxWord = null;
Integer maxCount = -1;
Map<String, Integer> wordCount = new HashMap<String, Integer>();
for (String str : getMyProgramOutput()) {
if (!wordCount.containsKey(str)) { wordCount.put(str, 0); }
int count = wordCount.get(str) + 1;
if (count > maxCount) {
maxWord = str;
maxCount = count;
}
wordCount.put(str, count);
}
Create a Map<String, Integer>. Every time you enter a String increment the Integer (you might have to create your own MutableInteger class. When you're finished search it (or keep a running count)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With