Vijay Kumar
Vijay Kumar

Reputation: 2707

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.

Upvotes: 2

Views: 270

Answers (2)

Janos Vinceller
Janos Vinceller

Reputation: 1266

If I understand you correctly, you want to count in your lamba. Sure, you can do that. Just initialize a count variable before executing the forEach and increase the count in your lambda block. Like this:

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

// fixed the long by this
final AtomicLong counter = new AtomicLong();
inReader.lines().forEach(line -> {
  counter.incrementAndGet();
  // do something with the line
});
// here you can do something with the count variable, like printing it out
System.out.printf("count=%d%n", counter.get());

The forEach method comes from Iterable. It is definiately not the way I would choose to process the reader. I would do something like this:

try (BufferedReader inReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"))) {
  Stream<String> lines = inReader.lines();
  
  long i = lines.peek(line -> {
        
        // do something with the line
     }).count();
  
  System.out.printf("count=%d%n", i);

}

PS: Didn't really test this, so correct me if I did a mistake.

Upvotes: 1

JohnSmith
JohnSmith

Reputation: 96

try this:

AtomicLong count = new AtomicLong();
lines.stream().forEach(line -> {
    count.getAndIncrement();
    // do something with line;
});

Upvotes: 0

Related Questions