Advertisement
DNNdrago

11. Most Frequent Word

May 25th, 2014
177
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.86 KB | None | 0 0
  1. import java.util.Map;
  2. import java.util.Scanner;
  3. import java.util.TreeMap;
  4.  
  5.  
  6. public class _11_MostFrequentWord {
  7.  
  8.     public static void main(String[] args) {
  9.         Scanner sc = new Scanner(System.in);
  10.         String[] words = sc.nextLine().toLowerCase().split("\\W+");
  11.        
  12.         Map<String, Integer> wordCounter = new TreeMap<>();
  13.        
  14.         for (String word : words) {
  15.             if(wordCounter.containsKey(word)) {
  16.                 wordCounter.put(word, wordCounter.get(word) + 1);
  17.             }
  18.             else
  19.                 wordCounter.put(word, 1);
  20.         }
  21.        
  22.         int mostFrequent = 0;
  23.         for (Map.Entry<String, Integer> word : wordCounter.entrySet()) {
  24.             if (mostFrequent < word.getValue())
  25.                 mostFrequent = word.getValue();
  26.         }
  27.        
  28.         for (Map.Entry<String, Integer> word : wordCounter.entrySet()) {
  29.             if (mostFrequent == word.getValue())
  30.                 System.out.println(word.getKey() + " -> " + word.getValue());
  31.         }
  32.     }
  33.  
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement