AlexKondov

Java Most Frequent Word

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