// This program counts the number of unique words in a file // and prints out information about how long it took to run import java.io.*; import java.util.*; public class UniqueWords { public static void main(String[] args) throws FileNotFoundException { System.out.println("Reading file..."); Scanner input = new Scanner(new File("mobydick.txt")); long start = System.currentTimeMillis(); int uniqueWords = countUnique(input); long end = System.currentTimeMillis(); long elapsed = end - start; System.out.println("The file has " + uniqueWords + " unique words."); System.out.println("Took " + elapsed + " ms."); } // post: returns the number of unique words that appear in the // given Scanner's data public static int countUnique(Scanner input) { /* // Code using a list: List list = new ArrayList<>(); while (input.hasNext()) { String word = input.next(); if (!list.contains(word) { list.add(word); } } return list.size(); */ // Improved code using a set! Set set = new HashSet<>(); while (input.hasNext()) { String word = input.next(); // don't need to check contains here, the set // ignores duplicates for us set.add(word); } return set.size(); } }