import java.io.File; import java.io.FileNotFoundException; import java.util.Collection; import java.util.Scanner; import java.util.Map; import java.util.HashMap; import java.util.TreeMap; /** * Reads in a text, and counts the number of occurences of * each word in it. Then, prints the words that are repeated * at least 300 times. * * @author Adam Blank */ public class CommonWordCount { public static void main(String[] args) throws FileNotFoundException { Scanner scanner = new Scanner(new File("alice.txt")); // word -> quantity // String -> Integer Map wordCounts = new HashMap<>(); while (scanner.hasNext()) { String word = scanner.next(); /* Check if the word is already a key. * If it isn't initialize its value to 0 */ if (!wordCounts.containsKey(word)) { wordCounts.put(word, 0); } /* We just saw the key; so, increment the count. */ wordCounts.put(word, wordCounts.get(word) + 1); } /* Print out all of the words that are in * the text more than 300 times. */ for (String key : wordCounts.keySet()) { if (wordCounts.get(key) > 300) { System.out.println(key + ": " + wordCounts.get(key)); } } } }