1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
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);
}
}