// CSE 143, Winter 2009, Marty Stepp // // This program counts the unique words in a large file and lets the // user search for words in that file. // It demonstrates the use of a Set collection. // // This version demonstrates the use of an Iterator object to examine the // collection and to remove some elements from it. import java.io.*; import java.util.*; public class WordCount2 { 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 Set words = new HashSet(); System.out.println("Reading file..."); Scanner input = new Scanner(new File("mobydick.txt")); while (input.hasNext()) { String word = input.next(); if (!words.contains(word)) { words.add(word); } } System.out.println(words.size() + " unique words total."); long endTime = System.currentTimeMillis(); System.out.println((endTime - startTime) + " ms elapsed."); // new/modified code here Iterator itr = words.iterator(); while (itr.hasNext()) { String word = itr.next(); if (word.endsWith("s")) { itr.remove(); } } System.out.println(words.size() + " unique words total."); } }