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

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

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

import javax.annotation.Nonnegative;
import javax.annotation.Nonnull;
import java.util.ArrayList;
import java.util.List;
import java.util.Spliterator;
import java.util.Spliterators.AbstractSpliterator;
import java.util.function.Consumer;
import java.util.function.Supplier;

public class Batch extends AbstractSpliterator> {

    @Nonnull
    private final Spliterator source;
    @Nonnull
    @Nonnegative
    private final Supplier batchSize;

    public Batch(
        @Nonnull Spliterator source,
        @Nonnegative @Nonnull Supplier batchSize
    ) {
        super(1, ORDERED | IMMUTABLE);
        this.source = source;
        this.batchSize = batchSize;
    }

    @Override
    public boolean tryAdvance(@Nonnull Consumer> consumer) {
        final int batchSize = batchSize().get();
        final List batch = new ArrayList<>(batchSize);
        for (int i = 0; i < batchSize; i++) {
            if (!source().tryAdvance(batch::add)) {
                if (!batch.isEmpty()) {
                    consumer.accept(batch);
                }
                return false;
            }
        }
        consumer.accept(batch);
        return true;
    }

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

    @Nonnull
    protected Supplier batchSize() {
        return batchSize;
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy