-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathCountingWords.java
43 lines (30 loc) · 1.09 KB
/
CountingWords.java
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
package com.zetcode;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.HashMap;
public class CountingWords {
public static void main(String[] args) throws IOException {
var wordCount = new HashMap<String, Integer>();
var fileName = "src/resources/thermopylae.txt";
var lines = Files.readAllLines(Paths.get(fileName),
StandardCharsets.UTF_8);
for (String line : lines) {
var words = line.split("\\s+");
for (String word : words) {
if (word.endsWith(".") || word.endsWith(",")) {
word = word.substring(0, word.length()-1);
}
if (wordCount.containsKey(word)) {
wordCount.put(word, wordCount.get(word) + 1);
} else {
wordCount.put(word, 1);
}
}
}
for (String key : wordCount.keySet()) {
System.out.println(key + ": " + wordCount.get(key));
}
}
}