Advertisement
Guest User

11. Most Frequent Word

a guest
May 21st, 2014
551
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.93 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.         try (Scanner scanner = new Scanner(System.in)) {
  10.             String[] words =  scanner.nextLine().split("\\W+");
  11.             TreeMap<String, Integer> wordOccurrences = new TreeMap<>();
  12.            
  13.             int maxWordCount = 0;
  14.             for (String word : words) {
  15.                 word = word.toLowerCase();
  16.                 Integer wordCount = wordOccurrences.get(word);
  17.                 if (wordCount == null) {
  18.                     wordCount = 0;
  19.                 }
  20.                 if (wordCount + 1 > maxWordCount) maxWordCount = wordCount + 1;
  21.                 wordOccurrences.put(word, wordCount + 1);
  22.             }
  23.            
  24.             for (Map.Entry<String, Integer> entry : wordOccurrences.entrySet()) {
  25.                 if (entry.getValue() == maxWordCount) {
  26.                     System.out.println(entry.getKey() + " -> "
  27.                             + maxWordCount + " times");
  28.                 }
  29.             }
  30.         } catch (Exception e) {
  31.             e.printStackTrace();
  32.         }
  33.     }
  34.  
  35. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement