// Example 130 from page 103 of Java Precisely second edition (The MIT Press 2005) // Author: Peter Sestoft (sestoft@itu.dk) import java.util.*; import java.io.*; // A concordance is a TreeMap mapping a word (a String) to a TreeSet // of linenumbers (Integer objects) class Example130 { public static void main(String[] args) throws IOException { if (args.length != 1) System.out.println("Usage: java Example130 "); else { SortedMap> index = buildIndex(args[0]); printIndex(index); } } // Parse alphanumeric words from the given file, and record them in // the index. The resulting index is a SortedMap from String to // SortedSet of Integer (the line numbers). static SortedMap> buildIndex(String filename) throws IOException { Reader r = new BufferedReader(new FileReader(filename)); StreamTokenizer stok = new StreamTokenizer(r); stok.quoteChar('"'); stok.ordinaryChars('!', '/'); stok.nextToken(); SortedMap> index = new TreeMap>(); // = new TreeMap>(new IgnoreCaseComparator()); while (stok.ttype != StreamTokenizer.TT_EOF) { if (stok.ttype == StreamTokenizer.TT_WORD) { SortedSet ts; if (index.containsKey(stok.sval)) // If word has a set, get it ts = index.get(stok.sval); else { ts = new TreeSet(); // Otherwise create one index.put(stok.sval, ts); } ts.add(stok.lineno()); } stok.nextToken(); } return index; } // Print the concordance index by iterating over its entries, and // for each entry, iterate over the value which is a set. static void printIndex(SortedMap> index) { for (Map.Entry> entry : index.entrySet()) { System.out.print(entry.getKey() + ": "); SortedSet lineNoSet = entry.getValue(); for (int lineno : lineNoSet) System.out.print(lineno + " "); System.out.println(); } } }