Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A java 8 stream that maps and collects all except the first item

I have a file format for potentially large files where the first line is special. I'd like to open the file once and treat it as a stream of lines, but handle the first line differently from all of the other lines. The others get map/collected, the first line needs to be just parsed into some flags. Is there a way?

This starts as:

result = Files.lines(path).map(something).collect(Collectors.toList());

except that I want to divert the first line.

like image 830
bmargulies Avatar asked May 11 '16 17:05

bmargulies


1 Answers

If you must only open the file once, the easiest thing to do is to make a BufferedReader, get the first line and then stream over the rest:

BufferedReader reader = Files.newBufferedReader(path);

String firstLine = reader.readLine();

result = reader.lines()
    .map(something)
    .collect(toList());
like image 86
Misha Avatar answered Sep 23 '22 15:09

Misha