Java-8 – how to skip from files Lines gets the even number of rows of the stream

In this case, there are only odd rows of meaningful data, and there are no characters that uniquely identify these rows My goal is to get something comparable to the following example:

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

Are there any "clean" practices that are not shared by global countries?

Solution

A clean approach is to further implement a splitter At this level, you can control the iteration through the flow element, and as long as one project is requested downstream, only two projects need to be iterated:

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

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

The solution has no side effects and retains the greatest advantage of the stream API, like lazy evaluation However, it should be clear that it does not have a useful semantics for unordered flow processing (please note the subtle aspect of using foreachordered instead of foreach when performing terminal operations on all elements), and in principle, it is unlikely to support parallel processing, which is very effective

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>