All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.echocat.jsu.TakeWhile Maven / Gradle / Ivy

There is a newer version: 2.0.6
Show newest version
package org.echocat.jsu;

import javax.annotation.Nonnull;
import java.util.Spliterator;
import java.util.Spliterators.AbstractSpliterator;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;
import java.util.function.Predicate;

public class TakeWhile extends AbstractSpliterator {

    @Nonnull
    private final Spliterator source;
    @Nonnull
    private final Predicate predicate;

    public TakeWhile(
        @Nonnull Spliterator source,
        @Nonnull Predicate predicate
    ) {
        super(1, ORDERED | IMMUTABLE);
        this.source = source;
        this.predicate = predicate;
    }

    @Override
    public boolean tryAdvance(@Nonnull Consumer consumer) {
        final AtomicReference reference = new AtomicReference<>();
        if (!source().tryAdvance(reference::set)) {
            return false;
        }
        if (!predicate().test(reference.get())) {
            return false;
        }
        consumer.accept(reference.get());
        return true;
    }

    @Nonnull
    protected Spliterator source() {
        return source;
    }

    @Nonnull
    protected Predicate predicate() {
        return predicate;
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy