// CSE 373, Winter 2013, Marty Stepp // This program counts occurrences of words in a file, then // finds the top words that occur the most times. // The program demonstrates the use of a Map. // It also demonstrates a "compound" collection, in this case, // a Map of Sets. import java.io.*; import java.util.*; public class Lecture03 { public static void main(String[] args) throws FileNotFoundException { // create a map of (word -> count of occurrences of that word) Map counts = new TreeMap(); Scanner input = new Scanner(new File("gettysburg.txt")); while (input.hasNext()) { String word = input.next(); if (!counts.containsKey(word)) { counts.put(word, 1); } else { int count = counts.get(word); count++; counts.put(word, count); } } // reverse the map... // (count -> word(s) that have that count) Map> revMap = new TreeMap>(); for (String word : counts.keySet()) { int count = counts.get(word); if (!revMap.containsKey(count)) { revMap.put(count, new TreeSet()); } revMap.get(count).add(word); } System.out.println(revMap); } }