Advertisement
Masovski

[Java Basics][Collections-HW] 11. Most Frequent Word

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