Read a file using Stream and keep track of the current index

dearn44 :

I am reading a large file as such:

try (Stream<String> stream = Files.lines(Paths.get(fileName))) {
    stream.skip(1).forEach(Main::parseLine);
} catch (IOException e) {
    e.printStackTrace();
}

where parse line looks like this:

private static void parseLine(String line) {
    System.out.println(line);
}

what I would like to do is also keep track of the current line I am reading and have parseLine look like this instead:

private static void parseLine(String line, int idx) {
    System.out.println(line);
}

How can I do this?

Ousmane D. :

Collect the lines to a list then use IntStream.range or an explicit for loop to call your method passing the element along with the index:

List<String> result = stream.skip(1).collect(Collectors.toList());    
IntStream.range(0, result.size())
         .forEach(i -> parseLine(result.get(i), i));

Another option would be to use the LineNumberReader API.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Using a Hashmap to keep track of original count or not

How to sort an array and keep track of the index in java

How to keep track of established connections using WebSockets

Using Handler to keep track of files

Is is possible to keep track of the current number of instances of a class?

How to read a stream from Azure File Store using Filehelpers

Using the Oracle SCN keep track of modified rows

C keep track of aio_read task

Read file inside current directory using Vue

How to keep track of the index of a numpy array element

node read stream a file from remote computer using ssh

Using metaclass to keep track of instances in python

Git keep the original file and not track any changes to it

Read multiple files but keep track of which file is which dataframe in R

When using a nested hash maps in dart how to keep track of the series of keys to get to the current nested map?

saving track titles of internet radio stream to file

Hadoop job chaining: Keep track of the job index

Read from a file or stream

How can I keep track of array index in for loop?

using retain to keep track of maximum value

Java: problems using stream to read a file

how to keep track of an item in a binary file

How to keep track of the last index in a binary search algorithm?

Create a file to keep track of task progress

Keep track of the last read record in MySQL

How to track file names on a media player playlist and get current playing file index

How to Keep Track of colem index when JTable has been Reordering?

How to keep track of previous index in a for loop? (rust)

Track writen data instead of read data in a file stream