Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert a counter into a Stream<String> .forEach()?

FileWriter writer = new FileWriter(output_file);     int i = 0;      try (Stream<String> lines = Files.lines(Paths.get(input_file))) {         lines.forEach(line -> {             try {                 writer.write(i + " # " + line + System.lineSeparator());             } catch (Exception e) {                 e.printStackTrace();             }            }                     );         writer.close();     } 

I need to write the line with the line number, so I tried to add a counter into the .forEach(), but I can't get it to work. I just don't know where to put the i++; into the code, randomly screwing around didn't help so far.

like image 914
Vega Avatar asked May 13 '15 09:05

Vega


People also ask

How do I add a counter in forEach loop?

Define an integer outside of the loop, and increment it inside of your loop. Use a for loop instead of foreach, which has a count for you: for(int i = 0; i < array. length; i++) { var item = array[i]; Console.

Can we use forEach in streams Java?

Stream forEach() method in Java with examplesStream forEach(Consumer action) performs an action for each element of the stream. Stream forEach(Consumer action) is a terminal operation i.e, it may traverse the stream to produce a result or a side-effect.

How do you continue a stream in forEach?

How to write continue statement inside forEach loop in java 8. A lambda expression is almost equivalent of instance of an anonymous class. Each iteration will call the overridden method in this instance. So if you want to continue, just return the method when condition is met.

How do you use counter in lambda expression?

If you really need to increment a counter from within a lambda, the typical way to do so is to make the counter an AtomicInteger or AtomicLong and then call one of the increment methods on it. You could use a single-element int or long array, but that would have race conditions if the stream is run in parallel.


1 Answers

You can use an AtomicInteger as a mutable final counter.

public void test() throws IOException {     // Make sure the writer closes.     try (FileWriter writer = new FileWriter("OutFile.txt") ) {         // Use AtomicInteger as a mutable line count.         final AtomicInteger count = new AtomicInteger();         // Make sure the stream closes.         try (Stream<String> lines = Files.lines(Paths.get("InFile.txt"))) {             lines.forEach(line -> {                         try {                             // Annotate with line number.                             writer.write(count.incrementAndGet() + " # " + line + System.lineSeparator());                         } catch (Exception e) {                             e.printStackTrace();                         }                     }             );         }     } } 
like image 174
OldCurmudgeon Avatar answered Sep 21 '22 09:09

OldCurmudgeon