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

org.jobrunr.utils.streams.StreamUtils Maven / Gradle / Ivy

package org.jobrunr.utils.streams;

import java.util.Collection;
import java.util.List;
import java.util.function.Consumer;
import java.util.stream.Collector;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public final class StreamUtils {

    private StreamUtils() {
    }

    /**
     * Creates a new batch collector
     *
     * @param batchSize      the batch size after which the batchProcessor should be called
     * @param batchProcessor the batch processor which accepts batches of records to process
     * @param             the type of elements being processed
     * @return a batch collector instance
     */
    public static  Collector, List> batchCollector(int batchSize, Consumer> batchProcessor) {
        return new BatchCollector<>(batchSize, batchProcessor);
    }

    public static  Stream ofType(Collection items, Class clazz) {
        return ofType(items.stream(), clazz);
    }

    public static  Stream ofType(Stream stream, Class clazz) {
        return stream
                .filter(clazz::isInstance)
                .map(clazz::cast);
    }

    public static  Collector single() {
        return Collectors.collectingAndThen(
                Collectors.toList(),
                list -> {
                    if (list.size() != 1) {
                        throw new IllegalStateException();
                    }
                    return list.get(0);
                }
        );
    }

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy