Count the number of occurrences of each word in the file

You need to write a program to count the number of occurrences of each word in the file using the stream api.

Author: Anton Sorokin, 2019-09-14

2 answers

The program counts the number of occurrences of each word in the file and outputs map of the form слово:количество вхождений.

Path path = Paths.get("file.txt"); //путь к файлу
Map<String, Integer> frequencyMap;

try (Stream<String> lineStream = Files.lines(path)) {
    frequencyMap = lineStream.collect(toMap(
            s -> s,
            s -> 1,
            Integer::sum));
} catch (IOException ignored) {
}
 1
Author: Anton Sorokin, 2019-09-14 05:27:11

The way @Anton Sorokin seems to count strings. This is how the words will be counted, but you need to adjust split() for yourself

Map<String, Long> cntMap;
try {
    cntMap = Files.lines(Paths.get("C:\\Temp\\text2.txt"))
                   // разделять по знакам пунктуации (!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~) или пробелу
                  .flatMap(l -> Stream.of(l.split("[\\p{Punct}\\s]")))
                  .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
    // обычный вывод
    cntMap.forEach((k, v) -> System.out.println(k + ":" + v));
    // сортированный вывод
    cntMap.entrySet().stream().sorted(Map.Entry.comparingByKey()).forEach(System.out::println);
} catch (IOException e) {
}
 0
Author: hinotf, 2019-09-14 09:07:53