// CSE 143, Winter 2009, Marty Stepp // // This program counts the occurrences of words in a large file and lets the // user know which words appeared 1000 times or more. // It demonstrates the use of a Map collection. import java.io.*; import java.util.*; public class WordCountWithMap { public static void main(String[] args) throws FileNotFoundException { // timer to see how long the program takes to run long startTime = System.currentTimeMillis(); // read file into a collection // word --> # of occurrences Map wordCount = new HashMap(); System.out.println("Reading file..."); Scanner input = new Scanner(new File("mobydick.txt")); while (input.hasNext()) { String word = input.next(); if (wordCount.containsKey(word)) { // seen this word before; increase count by 1 int count = wordCount.get(word); count++; wordCount.put(word, count); } else { // never seen this word before wordCount.put(word, 1); } } System.out.println(wordCount.size() + " unique words total."); System.out.println("Words that occur at least 1000 times:"); for (String word : wordCount.keySet()) { int count = wordCount.get(word); if (count >= 1000) { System.out.println(word + " occurs " + count + " times."); } } long endTime = System.currentTimeMillis(); System.out.println((endTime - startTime) + " ms elapsed."); } }