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

org.echocat.jsu.StreamUtils Maven / Gradle / Ivy

package org.echocat.jsu;

import javax.annotation.Nonnegative;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import java.util.List;
import java.util.function.Predicate;
import java.util.function.Supplier;
import java.util.stream.Stream;

import static java.util.stream.StreamSupport.stream;
import static org.echocat.jsu.Generator.Value.valueOf;

public final class StreamUtils {

    @Nonnull
    public static  Stream until(@Nonnull Stream source, @Nonnegative @Nonnull Predicate predicate) {
        return stream(SpliteratorUtils.until(source.spliterator(), predicate), false)
            .onClose(() -> closeQuietly(source));
    }

    @Nonnull
    public static  Stream> batch(@Nonnull Stream source, @Nonnegative @Nonnull Supplier batchSize) {
        //noinspection unchecked,rawtypes
        return (Stream) stream(SpliteratorUtils.batch(source.spliterator(), batchSize), false)
            .onClose(() -> closeQuietly(source));
    }

    @Nonnull
    public static  Stream> batch(@Nonnull Stream source, @Nonnegative int batchSize) {
        return batch(source, () -> batchSize);
    }

    @Nonnull
    public static  Stream generate(@Nonnull Generator generator) {
        //noinspection unchecked
        return (Stream) stream(SpliteratorUtils.generate(generator), false)
            .onClose(() -> closeQuietly(generator));
    }

    @Nonnull
    public static  Stream generate(@Nonnull Supplier supplier) {
        return generate(() -> valueOf(supplier.get()));
    }

    public static void closeQuietly(@Nullable Object closeable) {
        try {
            if (closeable instanceof AutoCloseable) {
                ((AutoCloseable) closeable).close();
            }
        } catch (final Exception ignored) {}
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy