// Tyler Mi // Short program showing the speed advantages of Sets over Lists // and introducing Maps for tallying import java.io.*; import java.util.*; public class WordCount { public static void main(String[] args) throws FileNotFoundException { File f = new File("moby.txt"); Scanner input = new Scanner(f); List list = new ArrayList<>(); int count = countUniqueWords(input, list); System.out.println(count); input = new Scanner(f); // Effectively resets Scanner to beginning of file Set set = new HashSet<>(); int count2 = countUniqueWords(input, set); System.out.println(count2); for (String word : set) { System.out.println(word); } input = new Scanner(f); // Effectively resets Scanner to beginning of file printCounts(input); } // Fills up the given List with the unique words from the given Scanner // and returns the total number of unique words public static int countUniqueWords(Scanner input, List words) { while(input.hasNext()) { String word = input.next(); if(!words.contains(word)) { words.add(word); } } return words.size(); } // Fills up the given Set with the unique words from the given Scanner // and returns the total number of unique words public static int countUniqueWords(Scanner input, Set words) { while(input.hasNext()) { String word = input.next(); words.add(word); } return words.size(); } // Prints the number of occurences each word appears in the given // input in alphabetical order public static void printCounts(Scanner input) { Map wordCounts = new TreeMap<>(); while(input.hasNext()) { String word = input.next(); // If we've never seen the word before, put in an initial count of 0 // for that word if (!wordCounts.containsKey(word)) { wordCounts.put(word, 0); } // Update the count for the word by 1 wordCounts.put(word, wordCounts.get(word) + 1); } // We can't traverse through the key-value pairs of the Map // so we traverse through just the keys for (String word : wordCounts.keySet()) { System.out.println(word + ": " + wordCounts.get(word) + " occurences"); } } }