Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

248
Views
Obteniendo un conteo de líneas mientras también procesa las líneas usando lambdas

Estoy tratando de obtener un recuento de las líneas procesadas por una lambda que itera sobre las líneas en un BufferedReader.

¿Hay alguna manera de obtener un conteo sin escribir la segunda lambda para obtener solo el conteo de líneas?

 final BufferedReader inReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")); inReader.lines().forEach(line -> { // do something with the line });

¿Puedo obtener un recuento también en el bloque de código anterior? Estoy usando Java 11.

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Si te entiendo bien, quieres contar en tu lamba. Claro, puedes hacer eso. Simplemente inicialice una variable de count antes de ejecutar forEach y aumente el count en su bloque lambda. Me gusta esto:

 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());

El método forEach proviene de Iterable . Definitivamente no es la forma en que elegiría procesar al lector. Yo haría algo como esto:

 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);

}

PD: Realmente no probé esto, así que corrígeme si cometí un error.

over 4 years ago · Santiago Trujillo Report

0

prueba esto:

 AtomicLong count = new AtomicLong(); lines.stream().forEach(line -> { count.getAndIncrement(); // do something with line; });
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!