Skip to content

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.


try this:

AtomicLong count = new AtomicLong(); -> {
    // do something with line;