Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

249
Visualizações
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 Respostas
Responde à pergunta

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 Relatório

0

try this:

AtomicLong count = new AtomicLong();
lines.stream().forEach(line -> {
    count.getAndIncrement();
    // do something with line;
});
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda