Source of WordFrequency.java


  1: import java.util.*; 
  2: import java.io.*; 
  3: 
  4: public class WordFrequency {
  5:   static public void main(String[] args) {
  6:     HashMap 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:     Set set = words.entrySet(); 
 27:     Iterator iter = set.iterator(); 
 28:     while (iter.hasNext()) {
 29:       Map.Entry entry = (Map.Entry) iter.next(); 
 30:       word = (String) entry.getKey();
 31:       count = (Count) entry.getValue(); 
 32:       System.out.println(word + 
 33:                          (word.length() < 8 ? "\t\t" : "\t") + 
 34:                          count.i); 
 35:     }
 36:   }
 37: 
 38:   static class Count {
 39:     Count(String word, int i) {
 40:       this.word = word; 
 41:       this.i = i; 
 42:     }
 43: 
 44:     String word; 
 45:     int i; 
 46:   }
 47: }