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

com.codepoetics.protonpack.MergingSpliterator Maven / Gradle / Ivy

There is a newer version: 1.16
Show newest version
package com.codepoetics.protonpack;

import java.util.ArrayList;
import java.util.List;
import java.util.Spliterator;
import java.util.function.BiFunction;
import java.util.function.Consumer;
import java.util.function.Supplier;
import java.util.stream.Stream;

class MergingSpliterator implements Spliterator {

    public static  Spliterator merging(Spliterator[] sources, Supplier unitSupplier, BiFunction merger) {
        return new MergingSpliterator<>(sources, unitSupplier, merger);
    }

    private final Spliterator[] sources;
    private final Supplier unitSupplier;
    private final BiFunction merger;

    private MergingSpliterator(Spliterator[] sources, Supplier unitSupplier, BiFunction merger) {
        this.sources = sources;
        this.unitSupplier = unitSupplier;
        this.merger = merger;
    }

    @Override
    public boolean tryAdvance(Consumer action) {
        List mergeables = new ArrayList<>(sources.length);
        Stream.of(sources).forEach(s -> s.tryAdvance(mergeables::add));

        if (mergeables.isEmpty()) {
            return false;
        }

        O unit = unitSupplier.get();

        action.accept(mergeables.stream().reduce(unit, merger,
                (l1, l2) -> l1)); // We never do this in parallel, so fuck it.
        return true;
    }

    @Override
    public Spliterator trySplit() {
        return null;
    }

    @Override
    public long estimateSize() {
        return Stream.of(sources).map(Spliterator::estimateSize).max(Long::compare).orElse(0L);
    }

    @Override
    public int characteristics() {
        return Spliterator.NONNULL & Spliterator.ORDERED & Spliterator.IMMUTABLE;
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy