First, the Java 8 stream is used, and then forEach (…) is called.

I have a CSV file, the first line contains the title So I think using java 8 stream is perfect

try (Stream<String> stream = Files.lines(csv_file) ){
        stream.skip(1).forEach( line -> handleLine(line) );
    } catch ( IOException ioe ){
        handleError(ioe);
    }

Can you get the first element, analyze it, and then call the forEach method? It's like

stream
      .forFirst( line -> handleFirst(line) )
      .skip(1)
      .forEach( line -> handleLine(line) );

In addition: my CSV file contains about 1K lines. I can process each line in parallel to speed up Except the first line I need the first line to initialize other objects in the project: / is it fast to open BufferedReader, read the first line, close BufferedReader and use parallel flow?

Solution

Typically, you can use iterators to do this:

Stream<Item> stream = ... //initialize your stream
Iterator<Item> i = stream.iterator();
handleFirst(i.next());
i.forEachRemaining(item -> handleRest(item));

In your program, it looks like this:

try (Stream<String> stream = Files.lines(csv_file)){
    Iterator<String> i = stream.iterator();
    handleFirst(i.next());
    i.forEachRemaining(s -> handleRest(s));
}

You may want to add some error checking in case you get 1 or 0 rows, but this should work

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>