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.
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.
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 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.
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.
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(); } } ); } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With