-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathWordCounter.java
More file actions
79 lines (68 loc) · 2.46 KB
/
WordCounter.java
File metadata and controls
79 lines (68 loc) · 2.46 KB
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class WordCounter {
private final File file;
private WordCounter(String name) {
file = new File(name);
}
private static Map<String, Integer> MyAccumulator(Map<String, Integer> previous, String next) {
if (previous.containsKey(next)) {
previous.put(next, previous.get(next) + 1);
} else {
previous.put(next, 1);
}
return previous;
}
private static Map<String, Integer> MyCombiner(Map<String, Integer> firstMap, Map<String, Integer> secondMap) {
for (String key : secondMap.keySet()) {
if (firstMap.containsKey(key)) {
firstMap.put(key, firstMap.get(key) + secondMap.get(key));
} else {
firstMap.put(key, secondMap.get(key));
}
}
return firstMap;
}
private Map<String, Integer> count() throws IOException {
return Files.lines(file.toPath())
.flatMap((l) -> Arrays.stream(l.split("[\\p{Punct}\\s…«»—]")))
.filter((w) -> w.length() > 0)
.map(String::toLowerCase)
.collect(HashMap::new,
WordCounter::MyAccumulator,
WordCounter::MyCombiner);
}
public static void main(String... args) {
File file = new File("vs.txt");
Map<String, Integer> map = new HashMap<>();
try {
Scanner scanner = new Scanner(file);
ArrayList<String> strings = new ArrayList<>();
while (scanner.hasNext()) {
strings.add(scanner.nextLine());
}
for (String string : strings) {
String[] words = string.toLowerCase().split("[\\p{Punct}\\s…«»—]");
for (String word : words) {
if (map.containsKey(word)) {
map.put(word, map.get(word) + 1);
} else if (!word.equals("")) {
map.put(word, 1);
}
}
}
WordCounter counter = new WordCounter("vs.txt");
if (map.equals(counter.count())) {
System.out.println("Works!");
}
} catch (IOException e) {
System.out.println("Error");
}
}
}