简体   繁体   中英

Count the number of words read from a file and stored in a list by accessing the list

I am reading from the disk and storing the contents of a file using:

BufferedReader br = Files.newBufferedReader(Paths.get(file)))

and then

list = br.lines().collect(Collectors.toList());

The list is accessible from other methods in the class. How do I use it to get the count of words read from the file. I have tried list.count() but it gives a wrong value.

I tried a few lambda functions even those were giving me only the count of distinct words but not the total word count. Any insights will be appreciated.

You read lines, not words.

If you want the number of words in a file, use

int numLines;
try (var lines = Files.lines(Path.of(file))) {
    numLines = lines.filter(l -> !l.isBlank()).mapToInt(w -> w.split("\\h").length).sum()
}

Since it's a list of lines, you will need a way of counting the words in a line:

private static int countWordsInLine(String line) {
    line = line.trim();
    return line.isEmpty() ? 0 : line.split("\\s+").length;
}

From there, you just need to sum over the lines in the list:

private int wordCount() {
    return lines.stream().mapToInt(ThisClass::countWordsInLine).sum();
}

Replace ThisClass with the name of the class that countWordsInLine is declared in.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM