Is it possible to partition a List in pure Jdk8 into equal chunks (sublists).
I know it is possible using Guava Lists class, but can we do it with pure Jdk? I don\'t wan
I have tried my own solution with a custom made Collector. I hope someone will find it useful, or help me improve it.
class PartitioningCollector implements Collector>, List>> {
private final int batchSize;
private final List batch;
public PartitioningCollector(int batchSize) {
this.batchSize = batchSize;
this.batch = new ArrayList<>(batchSize);
}
@Override
public Supplier>> supplier() {
return LinkedList::new;
}
@Override
public BiConsumer>, T> accumulator() {
return (total, element) -> {
batch.add(element);
if (batch.size() >= batchSize) {
total.add(new ArrayList<>(batch));
batch.clear();
}
};
}
@Override
public BinaryOperator>> combiner() {
return (left, right) -> {
List> result = new ArrayList<>();
result.addAll(left);
result.addAll(left);
return result;
};
}
@Override
public Function>, List>> finisher() {
return result -> {
if (!batch.isEmpty()) {
result.add(new ArrayList<>(batch));
batch.clear();
}
return result;
};
}
@Override
public Set characteristics() {
return emptySet();
}
}