Advertisement
dimipan80

11. Most Frequent Word

Sep 13th, 2014
290
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.50 KB | None | 0 0
  1. /* Write a program to find the most frequent word in a text and print it,
  2.  * as well as how many times it appears in format "word -> count".
  3.  * Consider any non-letter character as a word separator.
  4.  * Ignore the character casing. If several words have the same maximal frequency,
  5.  * print all of them in alphabetical order. */
  6.  
  7. import java.util.ArrayList;
  8. import java.util.Scanner;
  9. import java.util.TreeMap;
  10.  
  11. public class _11_MostFrequentWord {
  12.  
  13.     public static void main(String[] args) {
  14.         // TODO Auto-generated method stub
  15.         Scanner scan = new Scanner(System.in);
  16.         System.out.println("Enter your text on single line:");
  17.         String inputLine = scan.nextLine().toLowerCase();
  18.  
  19.         String[] text = inputLine.split("[^a-z]+");
  20.         TreeMap<String, Integer> frequentWords = new TreeMap<>();
  21.         for (String string : text) {
  22.             Integer times = frequentWords.get(string);
  23.             if (times == null) {
  24.                 times = 0;
  25.             }
  26.  
  27.             frequentWords.put(string, times + 1);
  28.         }
  29.  
  30.         ArrayList<String> mostFrequentWords = new ArrayList<>();
  31.         int maxTimesAppears = 1;
  32.         for (String key : frequentWords.keySet()) {
  33.             if (frequentWords.get(key) > maxTimesAppears) {
  34.                 maxTimesAppears = frequentWords.get(key);
  35.                 mostFrequentWords = new ArrayList<>();
  36.                 mostFrequentWords.add(key);
  37.             } else if (frequentWords.get(key) == maxTimesAppears) {
  38.                 mostFrequentWords.add(key);
  39.             }
  40.         }
  41.  
  42.         for (String word : mostFrequentWords) {
  43.             System.out.println(word + " -> " + frequentWords.get(word)
  44.                     + " times");
  45.         }
  46.     }
  47.  
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement