Source of WordFrequency4.java


  1: import java.util.*; 
  2: import java.io.*; 
  3: 
  4: public class WordFrequency4 {
  5:   static public void main(String[] args) {
  6:     Map words = new HashMap(); 
  7:     String delim = " \t\n.,:;?!-/()[]\"\'";
  8:     BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); 
  9:     String line, word;
 10:     Count count; 
 11:     try {
 12:       while ((line = in.readLine()) != null) {
 13:         StringTokenizer st = new StringTokenizer(line, delim); 
 14:         while (st.hasMoreTokens()) {
 15:           word = st.nextToken().toLowerCase(); 
 16:           count = (Count) words.get(word); 
 17:           if (count == null) {
 18:             words.put(word, new Count(word, 1)); 
 19:           } else {
 20:             count.i++; 
 21:         }
 22:       }
 23:     } 
 24:   } catch (IOException e) {}
 25:     
 26:     List list = new ArrayList(words.values()); 
 27:     Collections.sort(list, new CountComparator()); 
 28:     Iterator iter = list.iterator();
 29: 
 30:     while (iter.hasNext()) {
 31:       count = (Count) iter.next(); 
 32:       word = count.word;
 33:       System.out.println(word + 
 34:                          (word.length() < 8 ? "\t\t" : "\t") + 
 35:                          count.i); 
 36:     }
 37:   }
 38: 
 39:   static class Count {
 40:     Count(String word, int i) {
 41:       this.word = word; 
 42:       this.i = i; 
 43:     }
 44: 
 45:     String word; 
 46:     int i; 
 47:   }
 48: 
 49:   static class CountComparator implements Comparator {
 50:     public int compare(Object o1, Object o2) {
 51:       if (o1 != null && 
 52:           o2 != null && 
 53:           o1 instanceof Count && 
 54:           o2 instanceof Count) { 
 55:         Count c1 = (Count) o1; 
 56:         Count c2 = (Count) o2; 
 57:         return (c2.i - c1.i); 
 58:       } else {
 59:         return 0; 
 60:       }
 61:     }
 62:   }
 63: }