-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExample142.java
More file actions
63 lines (55 loc) · 2.07 KB
/
Example142.java
File metadata and controls
63 lines (55 loc) · 2.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
// Example 142 from page 113
//
import java.util.*;
import java.io.*;
// A concordance is a TreeMap mapping a word (a String) to a TreeSet
// of linenumbers (Integer objects)
class Example142 {
public static void main(String[] args) throws IOException {
if (args.length != 1)
System.out.println("Usage: java Example142 <filename>");
else {
SortedMap<String,SortedSet<Integer>> 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<String,SortedSet<Integer>> buildIndex(String filename)
throws IOException
{
Reader r = new BufferedReader(new FileReader(filename));
StreamTokenizer stok = new StreamTokenizer(r);
stok.quoteChar('"'); stok.ordinaryChars('!', '/');
stok.nextToken();
SortedMap<String,SortedSet<Integer>> index
= new TreeMap<String,SortedSet<Integer>>();
// = new TreeMap<String,SortedSet<Integer>>(new IgnoreCaseComparator());
while (stok.ttype != StreamTokenizer.TT_EOF) {
if (stok.ttype == StreamTokenizer.TT_WORD) {
SortedSet<Integer> ts;
if (index.containsKey(stok.sval)) // If word has a set, get it
ts = index.get(stok.sval);
else {
ts = new TreeSet<Integer>(); // 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<String,SortedSet<Integer>> index) {
for (Map.Entry<String,SortedSet<Integer>> entry : index.entrySet()) {
System.out.print(entry.getKey() + ": ");
SortedSet<Integer> lineNoSet = entry.getValue();
for (int lineno : lineNoSet)
System.out.print(lineno + " ");
System.out.println();
}
}
}