// CSE 143, winter 2012 // This program counts the number of words in a large file. // It demonstrates the use of a Set collection. import java.io.*; import java.util.*; public class WordCount { public static void main(String[] args) throws FileNotFoundException { // Original ArrayList version was O(n^2), now O(n) Set words = new HashSet(); long start = System.currentTimeMillis(); System.out.println("Reading file..."); Scanner input = new Scanner(new File("mobydick.txt")); while (input.hasNext()) { // if (!words.contains(word)) { words.add(input.next()); // } } long end = System.currentTimeMillis(); long elapsed = end - start; System.out.println("The file has " + words.size() + " words."); System.out.println("Took " + elapsed + " ms."); // For-each loop (for each word in the words collection...) /*for (String word : words) { System.out.println(word); }*/ } }