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

com.github.phantomthief.util.MoreStreams Maven / Gradle / Ivy

There is a newer version: 0.1.55
Show newest version
package com.github.phantomthief.util;

import static com.google.common.base.Preconditions.checkNotNull;
import static java.util.Spliterator.IMMUTABLE;
import static java.util.Spliterator.NONNULL;
import static java.util.Spliterator.ORDERED;
import static java.util.Spliterators.spliterator;
import static java.util.Spliterators.spliteratorUnknownSize;
import static java.util.stream.IntStream.rangeClosed;
import static java.util.stream.StreamSupport.stream;

import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.stream.IntStream;
import java.util.stream.LongStream;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;

import com.google.common.collect.Iterators;

/**
 * @author w.vela
 */
public class MoreStreams {

    private MoreStreams() {
        throw new UnsupportedOperationException();
    }

    public static LongStream longRangeClosed(long from, long to) {
        if (from <= to) {
            return LongStream.rangeClosed(from, to);
        } else {
            return LongStream.rangeClosed(to, from).map(i -> to - i + from);
        }
    }

    public static IntStream intRangeClosed(int from, int to) {
        if (from <= to) {
            return rangeClosed(from, to);
        } else {
            return rangeClosed(to, from).map(i -> to - i + from);
        }
    }

    public static  Stream toStream(Iterator iterator) {
        checkNotNull(iterator);
        return stream(spliteratorUnknownSize(iterator, (NONNULL | IMMUTABLE | ORDERED)), false);
    }

    public static  Stream toStream(Iterable iterable) {
        checkNotNull(iterable);
        if (iterable instanceof Collection) {
            // failfast
            try {
                Collection collection = (Collection) iterable;
                return stream(spliterator(collection, 0), false);
            } catch (Throwable e) {
                // do nothing
            }
        }
        return stream(spliteratorUnknownSize(iterable.iterator(), (NONNULL | IMMUTABLE | ORDERED)),
                false);
    }

    public static  Stream> partition(Stream stream, int size) {
        Iterable> iterable = () -> Iterators.partition(stream.iterator(), size);
        return StreamSupport.stream(iterable.spliterator(), false);
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy