Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to skip even lines of a Stream<String> obtained from the Files.lines

In this case just odd lines have meaningful data and there is no character that uniquely identifies those lines. My intention is to get something equivalent to the following example:

Stream<DomainObject> res = Files.lines(src)
     .filter(line -> isOddLine())
     .map(line -> toDomainObject(line))

Is there any “clean” way to do it, without sharing global state?

like image 910
Miguel Gamboa Avatar asked May 11 '15 14:05

Miguel Gamboa


1 Answers

No, there's no way to do this conveniently with the API. (Basically the same reason as to why there is no easy way of having a zipWithIndex, see Is there a concise way to iterate over a stream with indices in Java 8?).

You can still use Stream, but go for an iterator:

Iterator<String> iter = Files.lines(src).iterator();
while (iter.hasNext()) {
    iter.next();                  // discard
    toDomainObject(iter.next());  // use
}

(You might want to use try-with-resource on that stream though.)

like image 50
aioobe Avatar answered Nov 29 '22 08:11

aioobe