Search code examples
javaarraysstringbufferedreadertreemap

How can I print the most frequent word in a text using bufferedreader and treemap ? - Java


The text will contain only spaces and words.

Sample input:

thanks for the help \n
the car works now   \n
thanks              \n

Output: the - because it is lexicographic smaller than " thanks".

 public class Main {
     public static void main(String[] args) throws IOException {
         String line;
         String[] words = new String[100];
         Map < String, Integer > frequency = new HashMap < > ();
         BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
         while ((line = reader.readLine()) != null) {
             line = line.trim();
             if (!line.isEmpty()) {
                 words = line.split("\\W+");
                 for (String word: words) {
                     String processed = word.toLowerCase();
                     processed = processed.replace(",", "");

                     if (frequency.containsKey(processed)) {
                         frequency.put(processed,
                             frequency.get(processed) + 1);
                     } else {
                         frequency.put(processed, 1);
                     }
                 }
             }
         }
         int mostFrequentlyUsed = 0;
         String theWord = null;

         for (String word: frequency.keySet()) {
             Integer theVal = frequency.get(word);
             if (theVal > mostFrequentlyUsed) {
                 mostFrequentlyUsed = theVal;
                 theWord = word;
             } else if (theVal == mostFrequentlyUsed && word.length() <
                 theWord.length()) {
                 theWord = word;
                 mostFrequentlyUsed = theVal;
             }

         }
         System.out.printf(theWord);
     }
 }

I'm failing one test and I really don't know why that's why I needed another method.


Solution

  • In the title of your question you mention TreeMap but you are actually not using it.

    If you replace the line where you instantiate the map with

             NavigableMap < String, Integer > frequency = new TreeMap < > ();
    

    Then you can replace the for loop with a single query to the map:

    System.out.println(frequency.lastEntry().key)

    You can read the documentation here: https://docs.oracle.com/javase/8/docs/api/java/util/TreeMap.html#lastEntry--