Skip to content
Advertisement

Getting a count of lines while also processing the lines using lambdas

I am trying to get a count of lines that have been processed by a lambda iterating over lines in a BufferedReader.

Is there a way to get a count without writing the 2nd lambda to get just the line count?

        final BufferedReader inReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));

        inReader.lines().forEach(line -> {
            
            // do something with the line
         });

Can I get a count also in the above code block? I am using Java 11.

Advertisement

Answer

try this:

AtomicLong count = new AtomicLong();
lines.stream().forEach(line -> {
    count.getAndIncrement();
    // do something with line;
});
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement