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

org.agzamovr.collectors.NTileCollector Maven / Gradle / Ivy

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 comparator,
                          Collector 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 comparator) {
        return ntile(tiles, comparator, toList());
    }

    , R>
    Collector> ntile(int tiles,
                                   Collector downstream) {
        return ntile(tiles, nullsLast(Comparator.naturalOrder()), downstream);
    }

    
    Collector, List> ntile(int tiles,
                                         Comparator comparator,
                                         Collector downstream) {
        return Collector.of(ArrayList::new,
                List::add,
                CollectorEx::listCombiner,
                (list) -> ntileFinisher(list, tiles, comparator, downstream));
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy