MostCommonWord.java 1.31 KB
import java.io.File;
import java.io.FileNotFoundException;
import java.util.*;

public class MostCommonWord {
    private static final String BOOK_FILENAME = "data/alice.txt";

    public static void main(String[] args) throws FileNotFoundException {
        HashMap<String, Integer> ds = new HashMap<>();
        Scanner s = new Scanner(new File(BOOK_FILENAME));
        while (s.hasNext()) {
            String word = s.next();
            /*
            if (ds.containsKey(word)) {
                int whateverwasthere = ds.get(word);
               ds.put(word, whateverwasthere + 1);
            }
            else {
                ds.put(word, 1);
            }
            */
            /*
            if (!ds.containsKey(word)) {
                ds.put(word, 0);
            }
            ds.put(word, ds.get(word) + 1);
             */
            ds.put(word, 1 + ds.getOrDefault(word, 0));
            // if word in ds -> add 1
            // otherwise, set word to 1
        }
        // loop through the keys and keep track of the max
        int max = 0;
        String word = "";
        for (String w : ds.keySet()) {
            if (ds.get(w) > max) {
                max = ds.get(w);
                word = w;
            }
        }
        // print the word corresponding to the max
        System.out.println(word);
    }
}