/** * ======================================================================== * TestHashSet.javat: Use a HashSet to print all unique words in System.in. * * Author: Cay Horstmann * ======================================================================== */ import java.util.*; public class TestHashSet { public static void main(String[] args) { Set words = new HashSet(); // HashSet implements Set long totalTime = 0; // Use a Scanner to read words from standard input. // Keep track of the time, measured in milliseconds. Scanner in = new Scanner(System.in); while (in.hasNext()) { String word = in.next(); long callTime = System.currentTimeMillis(); words.add(word); callTime = System.currentTimeMillis() - callTime; totalTime += callTime; } // Print up to the first 20 words .... System.out.println("Print up to the first 20 distinct words "); System.out.println("======================================= "); Iterator iter = words.iterator(); for (int i = 1; i <= 20 && iter.hasNext(); i++) System.out.println(iter.next()); // Print number of distinct words ... System.out.println("======================================= "); System.out.println(words.size() + " distinct words. " + totalTime + " milliseconds."); System.out.println("======================================= "); } }