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

后端 未结 5 1176
醉酒成梦
醉酒成梦 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:18

    Following the @aioobe algorithm, here's another spliterator-based approach, as proposed by @Holger but more concise, even if less effective.

    public static  Stream filterOdd(Stream src) {
        Spliterator iter = src.spliterator();
        AbstractSpliterator res = new AbstractSpliterator(Long.MAX_VALUE, Spliterator.ORDERED)
        {
            @Override
            public boolean tryAdvance(Consumer action) {
                iter.tryAdvance(item -> {});    // discard
                return iter.tryAdvance(action); // use
            }
        };
        return StreamSupport.stream(res, false);
    }
    

    Then you can use it like

    Stream res = Files.lines(src)
    filterOdd(res)
     .map(line -> toDomainObject(line))
    

提交回复
热议问题