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

前端 未结 2 1739
日久生厌
日久生厌 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:49

    In my opinion, the simplest way to count the words in a file using Java 8 is this:

    Long wordsCount = Files.lines(Paths.get(file))
        .flatMap(str->Stream.of(str.split("[ ,.!?\r\n]")))
        .filter(s->s.length()>0).count();
    System.out.println(wordsCount);
    

    And to count all the files:

    Long filesCount = Files.walk(Paths.get(file)).count();
    System.out.println(filesCount);
    
    0 讨论(0)
  • 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();
    
    0 讨论(0)
提交回复
热议问题