How to count words in a text file, java 8-style

前端 未结 2 1738
日久生厌
日久生厌 2020-12-11 13:03

I\'m trying to perform an assignment that first counts the number of files in a directory and then give a word count within each file. I got the file count alright, but I\'m

2条回答
  •  囚心锁ツ
    2020-12-11 13:50

    Word count example:

    Files.lines(Paths.get(file))
        .flatMap(line -> Arrays.stream(line.trim().split(" ")))
        .map(word -> word.replaceAll("[^a-zA-Z]", "").toLowerCase().trim())
        .filter(word -> !word.isEmpty())
        .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));
    

    Files count:

    Files.walk(Paths.get(file), Integer.MAX_VALUE).count();
    Files.walk(Paths.get(file)).count();
    

提交回复
热议问题