Guest User

Untitled

a guest
May 24th, 2014
143
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.26 KB | None | 0 0
  1. import java.util.ArrayList;
  2. import java.util.Map;
  3. import java.util.Scanner;
  4. import java.util.TreeMap;
  5. import java.util.regex.Matcher;
  6. import java.util.regex.Pattern;
  7.  
  8.  
  9. public class _11_MostFrequentWord {
  10.  
  11.     public static void main(String[] args) {
  12.        
  13.         Scanner sc = new Scanner(System.in);
  14.        
  15.         String input = sc.nextLine().toLowerCase();
  16.        
  17.         Pattern regex = Pattern.compile("\\w+");
  18.         Matcher matcher = regex.matcher(input);
  19.         ArrayList<String> allWords = new ArrayList<>();
  20.        
  21.         while(matcher.find()){                              //Put all words in ArrayList
  22.             allWords.add(matcher.group());
  23.         }
  24.  
  25.         Map<String, Integer> result = new TreeMap<>();
  26.  
  27.         for(String word : allWords){                        //Make counter for every word
  28.             Integer count = result.get(word);
  29.             if(count == null){
  30.                 count = 0;
  31.             }
  32.             result.put(word, count + 1);
  33.         }
  34.        
  35.         int highestCount = 0;                               //Find the highest count of a word
  36.         for(String word : result.keySet()){
  37.             int count = result.get(word);
  38.             if(count > highestCount){
  39.                 highestCount = count;
  40.             }
  41.         }
  42.        
  43.        
  44.         for(String word : result.keySet()){                 //Print the word/s with highest count
  45.             int count = result.get(word);
  46.             if(count == highestCount){
  47.                 System.out.printf("%s -> %d times \n", word, count);
  48.             }
  49.         }
  50.     }
  51.  
  52. }
Advertisement
Add Comment
Please, Sign In to add comment