Java 8 threads are taken first and then call forEach (...)

I have a CSV file, and the first line contains the headers. So I thought it would be ideal to use Java 8 threads.

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

Is it possible to take the first element, parse it, and then call the forEach method? Sort of

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

OPTIONAL: My CSV file contains about 1 thousand lines, and I can process each line in parallel to speed it up. Except the first line. I need the first line to initialize other objects in my project: / So, maybe quickly open the BufferedReader, read the first line, close the BufferedReader and use parallel streams?

+4
source share
3 answers

, :

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

:

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

, , 1 0 , .

+6

BufferedReader , , Files.newBufferedReader(path). nextLine() , , lines(), Stream<String> :

try (BufferedReader br = Files.newBufferedReader(csv_file)){
    String header = br.readLine();
    // if header is null, the file was empty, you may want to throw an exception
    br.lines().forEach(line -> handleLine(line));
}

, readLine() , , lines() - , , . .

, , I/O, , , . forEach : , . , handleLine, , , forEach collect, .

+4

, , :

try (Stream<String> stream = Files.lines(csv_file) ){
    Iterator<String> iter = stream.iterator();
    if (iter.hasNext()) {
        handleFirst(iter.next());
        while (iter.hasNext()) {
            handleLine(iter.next());
        }
    }
} catch ( IOException ioe ){
    handleError(ioe);
}
0

Source: https://habr.com/ru/post/1662461/


All Articles