// adapted from Liang's "CountOccurrenceOfWords" example // (see my GUI notes for info on book) import java.util.*; public class CountWords { public static void main(String[] args) { // Text in a string with words to count: String text = "aaa bbb aaa bbb bbb ccc ddd"; // Create a hash map; // keys=words, values=counts: HashMap hashMap = new HashMap(); // Split text into individual words to // produce keys; use space (" ") to tokenize: StringTokenizer allKeys = new StringTokenizer(text); // For each word in text, // if it's "old", increment count // otherwise, create a key and start count while (allKeys.hasMoreTokens()) { // Current word to test: String key = allKeys.nextToken(); // Increment count if key's already in hm // (I split this up for clarity): if (hashMap.get(key) != null) { // Retrieve val corresponding to key: Object val = hashMap.get(key); // Create new value to store: int intVal = ((Integer)val).intValue(); // Increment value: intVal++; // Store it: hashMap.put(key, new Integer(intVal)); } else { // Create new key-value for hm: hashMap.put(key, new Integer(1)); } } // done creating hm // Create a tree map from the hash map: TreeMap treeMap = new TreeMap(hashMap); // Get an entry set for the tree map: Set entrySet = treeMap.entrySet(); // Get an iterator for the entry set: Iterator iterator = entrySet.iterator(); // Display mappings: System.out.println("Words and counts in " + "ascending order of words:"); while (iterator.hasNext()) { System.out.println(iterator.next()); } } // end main } // Class CountWords /* output: Words and counts in ascending order of words: aaa=2 bbb=3 ccc=1 ddd=1 */