Source of WordFrequency2.java


  1: 
  2: import java.util.*; 
  3: import java.io.*; 
  4: 
  5: public class WordFrequency2 {
  6:   static public void main(String[] args) {
  7:     //TreeMap words = new TreeMap(new StringComparator()); 
  8:     TreeMap words = new TreeMap(); 
  9:     String delim = " \t\n.,:;?!-/()[]\"\'";
 10:     BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); 
 11:     String line, word;
 12:     Count count; 
 13:     try {
 14:       while ((line = in.readLine()) != null) {
 15:         StringTokenizer st = new StringTokenizer(line, delim); 
 16:         while (st.hasMoreTokens()) {
 17:           word = st.nextToken().toLowerCase(); 
 18:           if (words.containsKey(word)) {
 19:             count = (Count) words.get(word); 
 20:             count.i++; 
 21:           } else {
 22:             words.put(word, new Count(word, 1)); 
 23:           }
 24:         }
 25:       } 
 26:     } catch (IOException e) {}
 27:     
 28:     Set set = words.entrySet(); 
 29:     Iterator iter = set.iterator(); 
 30:     while (iter.hasNext()) {
 31:       Map.Entry entry = (Map.Entry) iter.next(); 
 32:       word = (String) entry.getKey();
 33:       count = (Count) entry.getValue(); 
 34:       System.out.println(word + 
 35:                          (word.length() < 8 ? "\t\t" : "\t") + 
 36:                          count.i); 
 37:     }
 38: 
 39:   }
 40: 
 41:   static class Count {
 42:     Count(String word, int i) {
 43:       this.word = word; 
 44:       this.i = i; 
 45:     }
 46: 
 47:     String word; 
 48:     int i; 
 49:   }
 50: }