Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java - Most suitable data structure for finding the most frequent element

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

like image 831
Matt9Atkins Avatar asked Dec 07 '25 08:12

Matt9Atkins


2 Answers

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);
}
like image 130
maerics Avatar answered Dec 08 '25 20:12

maerics


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)

like image 45
James Avatar answered Dec 08 '25 22:12

James



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!