ru.shemplo.snowball.utils.fp.StreamUtils Maven / Gradle / Ivy
package ru.shemplo.snowball.utils.fp;
import static java.util.Spliterator.*;
import java.util.Iterator;
import java.util.Objects;
import java.util.Spliterator;
import java.util.Spliterators;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.stream.Stream;
import java.util.stream.StreamSupport;
public interface StreamUtils {
static Stream whilst (Predicate condition,
Function step, I obj) {
Stream.Builder builder = Stream.builder ();
while (condition.test (obj)) {
O tmp = step.apply (obj);
builder.add (tmp);
}
return builder.build ();
}
static Stream dowhilst (Predicate condition,
Function step, I obj) {
Stream.Builder builder = Stream.builder ();
O tmp = null;
do {
if (tmp != null) { builder.add (tmp); }
tmp = step.apply (obj);
} while (tmp != null && condition.test (tmp));
return builder.build ();
}
static , O> Stream takeIf (Predicate condition,
Function step, I obj) {
throw new UnsupportedOperationException ();
}
static AStream zip (Stream left, Stream right,
BiFunction zipper) {
Objects.requireNonNull (zipper);
Spliterator extends I1> aSpliterator = Objects.requireNonNull (left ).spliterator ();
Spliterator extends I2> bSpliterator = Objects.requireNonNull (right).spliterator ();
// Zipping looses DISTINCT and SORTED characteristics
int characteristics = aSpliterator.characteristics ()
& bSpliterator.characteristics ()
& ~(DISTINCT | SORTED);
long zipSize = ((characteristics & SIZED) != 0)
? Math.min (aSpliterator.getExactSizeIfKnown (),
bSpliterator.getExactSizeIfKnown ())
: -1;
Iterator aIterator = Spliterators.iterator (aSpliterator);
Iterator bIterator = Spliterators.iterator (bSpliterator);
Iterator cIterator = new Iterator () {
@Override
public boolean hasNext () {
return aIterator.hasNext () && bIterator.hasNext ();
}
@Override
public O next () {
return zipper.apply (aIterator.next (), bIterator.next ());
}
};
Spliterator split = Spliterators.spliterator (cIterator, zipSize, characteristics);
return AStreamProxy.make ((left.isParallel () || right.isParallel ())
? StreamSupport.stream (split, true)
: StreamSupport.stream (split, false));
}
}