com.github.phantomthief.util.MoreStreams Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of more-lambdas Show documentation
Show all versions of more-lambdas Show documentation
Some useful lambda implements for Java 8.
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