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

java-8, java-stream

Solution

A clean way is to go one level deeper and implement a `Spliterator`. On this level you can control the iteration over the stream elements and simply iterate over two items whenever the downstream requests one item:

public class OddLines<T> extends Spliterators.AbstractSpliterator<T>
    implements Consumer<T> {

    public static <T> Stream<T> oddLines(Stream<T> source) {
        return StreamSupport.stream(new OddLines(source.spliterator()), false);
    }
    private static long odd(long l) { return l==Long.MAX_VALUE? l: (l+1)/2; }
    Spliterator<T> originalLines;

    OddLines(Spliterator<T> source) {
        super(odd(source.estimateSize()), source.characteristics());
        originalLines=source;
    }

    @Override
    public boolean tryAdvance(Consumer<? super T> action) {
        if(originalLines==null || !originalLines.tryAdvance(action))
            return false;
        if(!originalLines.tryAdvance(this)) originalLines=null;
        return true;
    }

    @Override
    public void accept(T t) {}
}

Then you can use it like

Stream<DomainObject> res = OddLines.oddLines(Files.lines(src))
    .map(line -> toDomainObject(line));

This solution has no side effects and retains most advantages of the `Stream` API like the lazy evaluation. However, it should be clear that it hasn’t a useful semantics for unordered stream processing (beware about the subtle aspects like using `forEachOrdered` rather than `forEach` when performing a terminal action on all elements) and while supporting parallel processing in principle, it’s unlikely to be very efficient…

Problem

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?

Original source

Related problems