Advertisement
coasterka

#4MostFrequentWord

Jun 3rd, 2014
216
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.04 KB | None | 0 0
  1. import java.util.ArrayList;
  2. import java.util.Collections;
  3. import java.util.HashMap;
  4. import java.util.List;
  5. import java.util.Scanner;
  6.  
  7. public class MostFrequentWord {
  8.    
  9.     public static void main(String[] args){
  10.        
  11.         Scanner scan = new Scanner(System.in);
  12.         String[] input = (scan.nextLine()).split("\\W+");
  13.         HashMap<String , Integer> hashMap = new HashMap<>();
  14.         String tempWord = "";
  15.        
  16.         for (int i = 0; i < input.length; i++) {           
  17.             tempWord = input[i].toLowerCase();
  18.             if (hashMap.containsKey(tempWord)) {
  19.                 hashMap.put(tempWord, hashMap.get(tempWord) + 1);
  20.             }
  21.             else {
  22.                 hashMap.put(tempWord, 1);
  23.             }
  24.         }
  25.        
  26.         List<Integer> occurances = new ArrayList<Integer>();
  27.         occurances.addAll(hashMap.values());
  28.         int maxOccurance = Collections.max(occurances);
  29.        
  30.         List<String> words = new ArrayList<String>();
  31.         words.addAll(hashMap.keySet());
  32.        
  33.         for (int i = 0; i < occurances.size(); i++) {
  34.             if (occurances.get(i) == maxOccurance) {
  35.                 System.out.println(words.get(i) + " -> " + maxOccurance);
  36.             }
  37.         }      
  38.     }
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement