org.agzamovr.collectors.NTileCollector Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of collectorex Show documentation
Show all versions of collectorex Show documentation
Java Collectors extensions for using with Java 8 streams
The newest version!
package org.agzamovr.collectors;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.function.BiConsumer;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collector;
import static java.util.Comparator.nullsLast;
import static java.util.stream.Collectors.toList;
class NTileCollector {
static final NTileCollector N_TILE_COLLECTOR = new NTileCollector();
List ntileFinisher(List list,
int tiles,
Comparator super T> comparator,
Collector super T, A, R> downstream) {
list.sort(comparator);
int bucketSize = computeBucketSize(list.size(), tiles);
List result = new ArrayList<>();
Supplier downstreamSupplier = downstream.supplier();
Function downstreamFinisher = downstream.finisher();
BiConsumer downstreamAccumulator = downstream.accumulator();
A container = null;
for (int i = 0; i < list.size(); i++) {
if (i % bucketSize == 0) {
if (container != null)
result.add(downstreamFinisher.apply(container));
container = downstreamSupplier.get();
}
downstreamAccumulator.accept(container, list.get(i));
}
if (container != null)
result.add(downstreamFinisher.apply(container));
return result;
}
private int computeBucketSize(int size, int tiles) {
int r = (size % tiles == 0) ? 0 : 1;
return size / tiles + r;
}
>
Collector>> ntile(int tiles) {
return ntile(tiles, nullsLast(Comparator.naturalOrder()), toList());
}
Collector>> ntile(int tiles,
Comparator super T> comparator) {
return ntile(tiles, comparator, toList());
}
, R>
Collector> ntile(int tiles,
Collector super T, ?, R> downstream) {
return ntile(tiles, nullsLast(Comparator.naturalOrder()), downstream);
}
Collector, List> ntile(int tiles,
Comparator super T> comparator,
Collector super T, ?, R> downstream) {
return Collector.of(ArrayList::new,
List::add,
CollectorEx::listCombiner,
(list) -> ntileFinisher(list, tiles, comparator, downstream));
}
}