Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

250
Vistas
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.

over 4 years ago · Santiago Trujillo
2 Respuestas
Responde la pregunta

0

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.

over 4 years ago · Santiago Trujillo Denunciar

0

try this:

AtomicLong count = new AtomicLong();
lines.stream().forEach(line -> {
    count.getAndIncrement();
    // do something with line;
});
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda