FrequencyTable.java


Below is the syntax highlighted version of FrequencyTable.java from §3.5 Searching Applications.


/******************************************************************************
 *  Compilation:  javac FrequencyTable StdIn.java
 *  Execution:    java FrequencyTable < words.txt
 *  Dependencies: StdIn.java StdOut.java
 *
 *  Read in a list of words from standard input and print out
 *  each word and the number of times it appears.
 *
 *  % java Frequency < mobydick.txt | sort -rn | more
 *  13967 the
 *  6415 of
 *  6247 and
 *  4583 a
 *  4508 to
 *  4037 in
 *  2911 that
 *  2481 his
 *
 ******************************************************************************/

public class FrequencyTable<Key extends Comparable<Key>> {
    private ST<Key, Integer> st = new ST<Key, Integer>();

    // add 1 to the number of times key appears
    public void hit(Key key) {
        if (st.contains(key))
            st.put(key, st.get(key) + 1);
        else
            st.put(key, 1);
    }

    // return the number of times the key appears
    public int count(Key key) {
        if (st.contains(key)) return st.get(key);
        else                  return 0;
    }

    // print all the keys to standard output
    public void show() {
        for (Key key : st.keys())
            StdOut.println(st.get(key) + " " + key);
    }

    public static void main(String[] args) {
        FrequencyTable<String> freq = new FrequencyTable<String>();
        while (!StdIn.isEmpty()) {
            String key = StdIn.readString();
            freq.hit(key);
        }
        freq.show();
    }
}


Copyright © 2002–2016, Robert Sedgewick and Kevin Wayne.
Last updated: Tue Aug 30 10:09:18 EDT 2016.