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

后端 未结 5 1183
醉酒成梦
醉酒成梦 2020-12-19 01:50

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

5条回答
  •  长情又很酷
    2020-12-19 02:28

    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 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.)

提交回复
热议问题