11 Collections and Maps

11.1

import java.util.*;

public class UniqueCharacterCounter {

    /**
     * A cache, mapping strings to count results. The count values are
     * stored as Integer objects within the map.
     */
    static Map globalCache = new HashMap();

    public static int countUniqueCharacters(String aString) {
        Object cachedResult = globalCache.get(aString);
        if (cachedResult != null)
            return ((Integer) cachedResult).intValue();

        // Result was not in the cache, calculate it.
        int length = aString.length();
        Set occurred = new TreeSet();
        Set duplicates = new TreeSet();

        // Identify occurrences and duplicates for each character in string:
        for (int i=0; i<length;i++) {
            Character character = new Character(aString.charAt(i));
            if (duplicates.contains(character)) continue;
            boolean newOccurrence = occurred.add(character);
            if (!newOccurrence) duplicates.add(character);
        }

        // Remove duplicates from occurrence count to obtain result:
        occurred.removeAll(duplicates);
        int result = occurred.size();

        // Put result in cache before returning:
        globalCache.put(aString, new Integer(result));
        return result;
    }

    /**
     * A simple main method for the purpose of demonstrating the
     * effect of the <code>countUniqueCharacters()</code>
     * method. Prints the result of applying the operation on each
     * command line argument.
     */
    public static void main(String[] args) {
        int nArgs = args.length;
        for (int i=0; i<nArgs; i++) {
            String argument = args[i];
            int result = countUniqueCharacters(argument);
            System.out.println(argument + ": " + result);
        }
    }
}

11.2

import java.util.*;

public class Concordance {

    /** Map for the concordance. */
    public Map index = new HashMap();

    /** Add each character and its index to the concordance */
    public Concordance(String input) {
        for (int i=0; i<input.length(); ++i) {
            addEntry(input.charAt(i), i);
        }
    }

    /** Update the list of indices for a given character */
    void addEntry(char c, int pos) {
        Character key = new Character(c);
        List hits = (List) index.get(key);
        if (hits == null) {
            hits = new ArrayList();
            index.put(key, hits);
        }
        hits.add(new Integer(pos));
    }

    public static void main(String[] args) {
        StringBuffer input = new StringBuffer();
        for (int i=0; i<args.length; ++i)
            input.append(args[i]);
        Concordance conc = new Concordance(input.toString());
        System.out.println(conc.index);
    }
};