org.echocat.jsu.Batch Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of java-stream-utils Show documentation
Show all versions of java-stream-utils Show documentation
Utilities to handle Java Streams.
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 extends T> source;
@Nonnull
@Nonnegative
private final Supplier batchSize;
public Batch(
@Nonnull Spliterator extends T> source,
@Nonnegative @Nonnull Supplier batchSize
) {
super(1, ORDERED | IMMUTABLE);
this.source = source;
this.batchSize = batchSize;
}
@Override
public boolean tryAdvance(@Nonnull Consumer super List> 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 extends T> source() {
return source;
}
@Nonnull
protected Supplier batchSize() {
return batchSize;
}
}