java8.util.stream.ReferencePipeline Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of streamsupport Show documentation
Show all versions of streamsupport Show documentation
streamsupport is a backport of the Java 8 java.util.function (functional interfaces) and
java.util.stream (streams) API for Java 6 / 7 and Android developers
The newest version!
/*
* Copyright (c) 2012, 2020, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
package java8.util.stream;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java8.util.Objects;
import java8.util.function.BiConsumer;
import java8.util.function.BiFunction;
import java8.util.function.BinaryOperator;
import java8.util.function.BinaryOperators;
import java8.util.function.Consumer;
import java8.util.function.DoubleConsumer;
import java8.util.function.Function;
import java8.util.function.IntConsumer;
import java8.util.function.IntFunction;
import java8.util.function.LongConsumer;
import java8.util.function.Predicate;
import java8.util.function.Supplier;
import java8.util.function.ToDoubleFunction;
import java8.util.function.ToIntFunction;
import java8.util.function.ToLongFunction;
import java8.util.Optional;
import java8.util.Spliterator;
import java8.util.Spliterators;
/**
* Abstract base class for an intermediate pipeline stage or pipeline source
* stage implementing whose elements are of type {@code U}.
*
* @param type of elements in the upstream source
* @param type of elements in produced by this stage
*
* @since 1.8
*/
abstract class ReferencePipeline
extends AbstractPipeline>
implements Stream {
/**
* Constructor for the head of a stream pipeline.
*
* @param source {@code Supplier} describing the stream source
* @param sourceFlags the source flags for the stream source, described in
* {@link StreamOpFlag}
* @param parallel {@code true} if the pipeline is parallel
*/
ReferencePipeline(Supplier extends Spliterator>> source,
int sourceFlags, boolean parallel) {
super(source, sourceFlags, parallel);
}
/**
* Constructor for the head of a stream pipeline.
*
* @param source {@code Spliterator} describing the stream source
* @param sourceFlags The source flags for the stream source, described in
* {@link StreamOpFlag}
* @param parallel {@code true} if the pipeline is parallel
*/
ReferencePipeline(Spliterator> source,
int sourceFlags, boolean parallel) {
super(source, sourceFlags, parallel);
}
/**
* Constructor for appending an intermediate operation onto an existing
* pipeline.
*
* @param upstream the upstream element source.
*/
ReferencePipeline(AbstractPipeline, P_IN, ?> upstream, int opFlags) {
super(upstream, opFlags);
}
// Shape-specific methods
@Override
final StreamShape getOutputShape() {
return StreamShape.REFERENCE;
}
@Override
final Node evaluateToNode(PipelineHelper helper,
Spliterator spliterator,
boolean flattenTree,
IntFunction generator) {
return Nodes.collect(helper, spliterator, flattenTree, generator);
}
@Override
final Spliterator wrap(PipelineHelper ph,
Supplier> supplier,
boolean isParallel) {
return new StreamSpliterators.WrappingSpliterator<>(ph, supplier, isParallel);
}
@Override
final Spliterator lazySpliterator(Supplier extends Spliterator> supplier) {
return new StreamSpliterators.DelegatingSpliterator<>(supplier);
}
@Override
final boolean forEachWithCancel(Spliterator spliterator, Sink sink) {
boolean cancelled;
do { } while (!(cancelled = sink.cancellationRequested()) && spliterator.tryAdvance(sink));
return cancelled;
}
@Override
final Node.Builder makeNodeBuilder(long exactSizeIfKnown, IntFunction generator) {
return Nodes.builder(exactSizeIfKnown, generator);
}
// BaseStream
@Override
public final Iterator iterator() {
return Spliterators.iterator(spliterator());
}
// Stream
// Stateless intermediate operations from Stream
@Override
public Stream unordered() {
if (!isOrdered())
return this;
return new StatelessOp(this, StreamShape.REFERENCE, StreamOpFlag.NOT_ORDERED) {
@Override
Sink opWrapSink(int flags, Sink sink) {
return sink;
}
};
}
@Override
public final Stream filter(Predicate super P_OUT> predicate) {
Objects.requireNonNull(predicate);
return new StatelessOp(this, StreamShape.REFERENCE,
StreamOpFlag.NOT_SIZED) {
@Override
Sink opWrapSink(int flags, Sink sink) {
return new Sink.ChainedReference(sink) {
@Override
public void begin(long size) {
downstream.begin(-1);
}
@Override
public void accept(P_OUT u) {
if (predicate.test(u))
downstream.accept(u);
}
};
}
};
}
@Override
public final Stream map(Function super P_OUT, ? extends R> mapper) {
Objects.requireNonNull(mapper);
return new StatelessOp(this, StreamShape.REFERENCE,
StreamOpFlag.NOT_SORTED | StreamOpFlag.NOT_DISTINCT) {
@Override
Sink opWrapSink(int flags, Sink sink) {
return new Sink.ChainedReference(sink) {
@Override
public void accept(P_OUT u) {
downstream.accept(mapper.apply(u));
}
};
}
};
}
@Override
public final IntStream mapToInt(ToIntFunction super P_OUT> mapper) {
Objects.requireNonNull(mapper);
return new IntPipeline.StatelessOp(this, StreamShape.REFERENCE,
StreamOpFlag.NOT_SORTED | StreamOpFlag.NOT_DISTINCT) {
@Override
Sink opWrapSink(int flags, Sink sink) {
return new Sink.ChainedReference(sink) {
@Override
public void accept(P_OUT u) {
downstream.accept(mapper.applyAsInt(u));
}
};
}
};
}
@Override
public final LongStream mapToLong(ToLongFunction super P_OUT> mapper) {
Objects.requireNonNull(mapper);
return new LongPipeline.StatelessOp(this, StreamShape.REFERENCE,
StreamOpFlag.NOT_SORTED | StreamOpFlag.NOT_DISTINCT) {
@Override
Sink opWrapSink(int flags, Sink sink) {
return new Sink.ChainedReference(sink) {
@Override
public void accept(P_OUT u) {
downstream.accept(mapper.applyAsLong(u));
}
};
}
};
}
@Override
public final DoubleStream mapToDouble(ToDoubleFunction super P_OUT> mapper) {
Objects.requireNonNull(mapper);
return new DoublePipeline.StatelessOp(this, StreamShape.REFERENCE,
StreamOpFlag.NOT_SORTED | StreamOpFlag.NOT_DISTINCT) {
@Override
Sink opWrapSink(int flags, Sink sink) {
return new Sink.ChainedReference(sink) {
@Override
public void accept(P_OUT u) {
downstream.accept(mapper.applyAsDouble(u));
}
};
}
};
}
@Override
public final Stream flatMap(Function super P_OUT, ? extends Stream extends R>> mapper) {
Objects.requireNonNull(mapper);
return new StatelessOp(this, StreamShape.REFERENCE,
StreamOpFlag.NOT_SORTED | StreamOpFlag.NOT_DISTINCT | StreamOpFlag.NOT_SIZED) {
@Override
Sink opWrapSink(int flags, Sink sink) {
return new Sink.ChainedReference(sink) {
// true if cancellationRequested() has been called
boolean cancellationRequested;
@Override
public void begin(long size) {
downstream.begin(-1);
}
@Override
public void accept(P_OUT u) {
Stream extends R> result = null;
try {
result = mapper.apply(u);
if (result != null) {
if (!cancellationRequested) {
result.sequential().forEach(downstream);
}
else {
Spliterator extends R> s = result.sequential().spliterator();
do { } while (!downstream.cancellationRequested() && s.tryAdvance(downstream));
}
}
} finally {
if (result != null) {
result.close();
}
}
}
@Override
public boolean cancellationRequested() {
// If this method is called then an operation within the stream
// pipeline is short-circuiting (see AbstractPipeline.copyInto).
// Note that we cannot differentiate between an upstream or
// downstream operation
cancellationRequested = true;
return downstream.cancellationRequested();
}
};
}
};
}
@Override
public final IntStream flatMapToInt(Function super P_OUT, ? extends IntStream> mapper) {
Objects.requireNonNull(mapper);
return new IntPipeline.StatelessOp(this, StreamShape.REFERENCE,
StreamOpFlag.NOT_SORTED | StreamOpFlag.NOT_DISTINCT | StreamOpFlag.NOT_SIZED) {
@Override
Sink opWrapSink(int flags, Sink sink) {
return new Sink.ChainedReference(sink) {
// true if cancellationRequested() has been called
boolean cancellationRequested;
// cache the consumer to avoid creation on every accepted element
IntConsumer downstreamAsInt = downstream::accept;
@Override
public void begin(long size) {
downstream.begin(-1);
}
@Override
public void accept(P_OUT u) {
IntStream result = null;
try {
result = mapper.apply(u);
if (result != null) {
if (!cancellationRequested) {
result.sequential().forEach(downstreamAsInt);
}
else {
Spliterator.OfInt s = result.sequential().spliterator();
do { } while (!downstream.cancellationRequested() && s.tryAdvance(downstreamAsInt));
}
}
} finally {
if (result != null) {
result.close();
}
}
}
@Override
public boolean cancellationRequested() {
cancellationRequested = true;
return downstream.cancellationRequested();
}
};
}
};
}
@Override
public final DoubleStream flatMapToDouble(Function super P_OUT, ? extends DoubleStream> mapper) {
Objects.requireNonNull(mapper);
return new DoublePipeline.StatelessOp(this, StreamShape.REFERENCE,
StreamOpFlag.NOT_SORTED | StreamOpFlag.NOT_DISTINCT | StreamOpFlag.NOT_SIZED) {
@Override
Sink opWrapSink(int flags, Sink sink) {
return new Sink.ChainedReference(sink) {
// true if cancellationRequested() has been called
boolean cancellationRequested;
// cache the consumer to avoid creation on every accepted element
DoubleConsumer downstreamAsDouble = downstream::accept;
@Override
public void begin(long size) {
downstream.begin(-1);
}
@Override
public void accept(P_OUT u) {
DoubleStream result = null;
try {
result = mapper.apply(u);
if (result != null) {
if (!cancellationRequested) {
result.sequential().forEach(downstreamAsDouble);
}
else {
Spliterator.OfDouble s = result.sequential().spliterator();
do { } while (!downstream.cancellationRequested() && s.tryAdvance(downstreamAsDouble));
}
}
} finally {
if (result != null) {
result.close();
}
}
}
@Override
public boolean cancellationRequested() {
cancellationRequested = true;
return downstream.cancellationRequested();
}
};
}
};
}
@Override
public final LongStream flatMapToLong(Function super P_OUT, ? extends LongStream> mapper) {
Objects.requireNonNull(mapper);
return new LongPipeline.StatelessOp(this, StreamShape.REFERENCE,
StreamOpFlag.NOT_SORTED | StreamOpFlag.NOT_DISTINCT | StreamOpFlag.NOT_SIZED) {
@Override
Sink opWrapSink(int flags, Sink sink) {
return new Sink.ChainedReference(sink) {
// true if cancellationRequested() has been called
boolean cancellationRequested;
// cache the consumer to avoid creation on every accepted element
LongConsumer downstreamAsLong = downstream::accept;
@Override
public void begin(long size) {
downstream.begin(-1);
}
@Override
public void accept(P_OUT u) {
LongStream result = null;
try {
result = mapper.apply(u);
if (result != null) {
if (!cancellationRequested) {
result.sequential().forEach(downstreamAsLong);
}
else {
Spliterator.OfLong s = result.sequential().spliterator();
do { } while (!downstream.cancellationRequested() && s.tryAdvance(downstreamAsLong));
}
}
} finally {
if (result != null) {
result.close();
}
}
}
@Override
public boolean cancellationRequested() {
cancellationRequested = true;
return downstream.cancellationRequested();
}
};
}
};
}
@Override
public final Stream mapMulti(BiConsumer super P_OUT, ? super Consumer> mapper) {
Objects.requireNonNull(mapper);
return new StatelessOp(this, StreamShape.REFERENCE,
StreamOpFlag.NOT_SORTED | StreamOpFlag.NOT_DISTINCT | StreamOpFlag.NOT_SIZED) {
@Override
Sink opWrapSink(int flags, Sink sink) {
return new Sink.ChainedReference(sink) {
@Override
public void begin(long size) {
downstream.begin(-1);
}
@Override
@SuppressWarnings("unchecked")
public void accept(P_OUT u) {
mapper.accept(u, (Consumer) downstream);
}
};
}
};
}
@Override
public final IntStream mapMultiToInt(BiConsumer super P_OUT, ? super IntConsumer> mapper) {
Objects.requireNonNull(mapper);
return new IntPipeline.StatelessOp(this, StreamShape.REFERENCE,
StreamOpFlag.NOT_SORTED | StreamOpFlag.NOT_DISTINCT | StreamOpFlag.NOT_SIZED) {
@Override
Sink opWrapSink(int flags, Sink sink) {
return new Sink.ChainedReference(sink) {
@Override
public void begin(long size) {
downstream.begin(-1);
}
@Override
public void accept(P_OUT u) {
mapper.accept(u, (IntConsumer)downstream);
}
};
}
};
}
@Override
public final LongStream mapMultiToLong(BiConsumer super P_OUT, ? super LongConsumer> mapper) {
Objects.requireNonNull(mapper);
return new LongPipeline.StatelessOp(this, StreamShape.REFERENCE,
StreamOpFlag.NOT_SORTED | StreamOpFlag.NOT_DISTINCT | StreamOpFlag.NOT_SIZED) {
@Override
Sink opWrapSink(int flags, Sink sink) {
return new Sink.ChainedReference(sink) {
@Override
public void begin(long size) {
downstream.begin(-1);
}
@Override
public void accept(P_OUT u) {
mapper.accept(u, (LongConsumer) downstream);
}
};
}
};
}
@Override
public final DoubleStream mapMultiToDouble(BiConsumer super P_OUT, ? super DoubleConsumer> mapper) {
Objects.requireNonNull(mapper);
return new DoublePipeline.StatelessOp(this, StreamShape.REFERENCE,
StreamOpFlag.NOT_SORTED | StreamOpFlag.NOT_DISTINCT | StreamOpFlag.NOT_SIZED) {
@Override
Sink opWrapSink(int flags, Sink sink) {
return new Sink.ChainedReference(sink) {
@Override
public void begin(long size) {
downstream.begin(-1);
}
@Override
public void accept(P_OUT u) {
mapper.accept(u, (DoubleConsumer) downstream);
}
};
}
};
}
@Override
public final Stream peek(Consumer super P_OUT> action) {
Objects.requireNonNull(action);
return new StatelessOp(this, StreamShape.REFERENCE,
0) {
@Override
Sink opWrapSink(int flags, Sink sink) {
return new Sink.ChainedReference(sink) {
@Override
public void accept(P_OUT u) {
action.accept(u);
downstream.accept(u);
}
};
}
};
}
// Stateful intermediate operations from Stream
@Override
public final Stream distinct() {
return DistinctOps.makeRef(this);
}
@Override
public final Stream sorted() {
return SortedOps.makeRef(this);
}
@Override
public final Stream sorted(Comparator super P_OUT> comparator) {
return SortedOps.makeRef(this, comparator);
}
@Override
public final Stream limit(long maxSize) {
if (maxSize < 0)
throw new IllegalArgumentException(Long.toString(maxSize));
return SliceOps.makeRef(this, 0, maxSize);
}
@Override
public final Stream skip(long n) {
if (n < 0)
throw new IllegalArgumentException(Long.toString(n));
if (n == 0)
return this;
else
return SliceOps.makeRef(this, n, -1);
}
@Override
public final Stream takeWhile(Predicate super P_OUT> predicate) {
return WhileOps.makeTakeWhileRef(this, predicate);
}
@Override
public final Stream dropWhile(Predicate super P_OUT> predicate) {
return WhileOps.makeDropWhileRef(this, predicate);
}
// Terminal operations from Stream
@Override
public void forEach(Consumer super P_OUT> action) {
evaluate(ForEachOps.makeRef(action, false));
}
@Override
public void forEachOrdered(Consumer super P_OUT> action) {
evaluate(ForEachOps.makeRef(action, true));
}
@Override
@SuppressWarnings("unchecked")
public final A[] toArray(IntFunction generator) {
// Since A has no relation to U (not possible to declare that A is an upper bound of U)
// there will be no static type checking.
// Therefore use a raw type and assume A == U rather than propagating the separation of A and U
// throughout the code-base.
// The runtime type of U is never checked for equality with the component type of the runtime type of A[].
// Runtime checking will be performed when an element is stored in A[], thus if A is not a
// super type of U an ArrayStoreException will be thrown.
@SuppressWarnings("rawtypes")
IntFunction rawGenerator = (IntFunction) generator;
return (A[]) Nodes.flatten((Node) evaluateToArrayNode(rawGenerator), generator)
.asArray(rawGenerator);
}
@Override
public final Object[] toArray() {
return toArray(Object[]::new);
}
@Override
public List toList() {
return Collectors.listFromTrustedArrayNullsAllowed(this.toArray());
}
@Override
public final boolean anyMatch(Predicate super P_OUT> predicate) {
return evaluate(MatchOps.makeRef(predicate, MatchOps.MatchKind.ANY));
}
@Override
public final boolean allMatch(Predicate super P_OUT> predicate) {
return evaluate(MatchOps.makeRef(predicate, MatchOps.MatchKind.ALL));
}
@Override
public final boolean noneMatch(Predicate super P_OUT> predicate) {
return evaluate(MatchOps.makeRef(predicate, MatchOps.MatchKind.NONE));
}
@Override
public final Optional findFirst() {
return evaluate(FindOps.makeRef(true));
}
@Override
public final Optional findAny() {
return evaluate(FindOps.makeRef(false));
}
@Override
public final P_OUT reduce(P_OUT identity, BinaryOperator accumulator) {
return evaluate(ReduceOps.makeRef(identity, accumulator, accumulator));
}
@Override
public final Optional reduce(BinaryOperator accumulator) {
return evaluate(ReduceOps.makeRef(accumulator));
}
@Override
public final R reduce(R identity, BiFunction accumulator, BinaryOperator combiner) {
return evaluate(ReduceOps.makeRef(identity, accumulator, combiner));
}
@Override
@SuppressWarnings("unchecked")
public final R collect(Collector super P_OUT, A, R> collector) {
A container;
if (isParallel()
&& (collector.characteristics().contains(Collector.Characteristics.CONCURRENT))
&& (!isOrdered() || collector.characteristics().contains(Collector.Characteristics.UNORDERED))) {
container = collector.supplier().get();
BiConsumer accumulator = collector.accumulator();
forEach(u -> accumulator.accept(container, u));
}
else {
container = evaluate(ReduceOps.makeRef(collector));
}
return collector.characteristics().contains(Collector.Characteristics.IDENTITY_FINISH)
? (R) container
: collector.finisher().apply(container);
}
@Override
public final R collect(Supplier supplier,
BiConsumer accumulator,
BiConsumer combiner) {
return evaluate(ReduceOps.makeRef(supplier, accumulator, combiner));
}
@Override
public final Optional max(Comparator super P_OUT> comparator) {
return reduce(BinaryOperators.maxBy(comparator));
}
@Override
public final Optional min(Comparator super P_OUT> comparator) {
return reduce(BinaryOperators.minBy(comparator));
}
@Override
public final long count() {
return evaluate(ReduceOps.makeRefCounting());
}
//
/**
* Source stage of a ReferencePipeline.
*
* @param type of elements in the upstream source
* @param type of elements in produced by this stage
* @since 1.8
*/
static class Head extends ReferencePipeline {
/**
* Constructor for the source stage of a Stream.
*
* @param source {@code Supplier} describing the stream
* source
* @param sourceFlags the source flags for the stream source, described
* in {@link StreamOpFlag}
*/
Head(Supplier extends Spliterator>> source,
int sourceFlags, boolean parallel) {
super(source, sourceFlags, parallel);
}
/**
* Constructor for the source stage of a Stream.
*
* @param source {@code Spliterator} describing the stream source
* @param sourceFlags the source flags for the stream source, described
* in {@link StreamOpFlag}
*/
Head(Spliterator> source,
int sourceFlags, boolean parallel) {
super(source, sourceFlags, parallel);
}
@Override
final boolean opIsStateful() {
throw new UnsupportedOperationException();
}
@Override
final Sink opWrapSink(int flags, Sink sink) {
throw new UnsupportedOperationException();
}
// Optimized sequential terminal operations for the head of the pipeline
@Override
public void forEach(Consumer super E_OUT> action) {
if (!isParallel()) {
sourceStageSpliterator().forEachRemaining(action);
}
else {
super.forEach(action);
}
}
@Override
public void forEachOrdered(Consumer super E_OUT> action) {
if (!isParallel()) {
sourceStageSpliterator().forEachRemaining(action);
}
else {
super.forEachOrdered(action);
}
}
}
/**
* Base class for a stateless intermediate stage of a Stream.
*
* @param type of elements in the upstream source
* @param type of elements in produced by this stage
* @since 1.8
*/
abstract static class StatelessOp
extends ReferencePipeline {
/**
* Construct a new Stream by appending a stateless intermediate
* operation to an existing stream.
*
* @param upstream The upstream pipeline stage
* @param inputShape The stream shape for the upstream pipeline stage
* @param opFlags Operation flags for the new stage
*/
StatelessOp(AbstractPipeline, E_IN, ?> upstream,
StreamShape inputShape,
int opFlags) {
super(upstream, opFlags);
}
@Override
final boolean opIsStateful() {
return false;
}
}
/**
* Base class for a stateful intermediate stage of a Stream.
*
* @param type of elements in the upstream source
* @param type of elements in produced by this stage
* @since 1.8
*/
abstract static class StatefulOp
extends ReferencePipeline {
/**
* Construct a new Stream by appending a stateful intermediate operation
* to an existing stream.
* @param upstream The upstream pipeline stage
* @param inputShape The stream shape for the upstream pipeline stage
* @param opFlags Operation flags for the new stage
*/
StatefulOp(AbstractPipeline, E_IN, ?> upstream,
StreamShape inputShape,
int opFlags) {
super(upstream, opFlags);
}
@Override
final boolean opIsStateful() {
return true;
}
@Override
abstract Node opEvaluateParallel(PipelineHelper helper,
Spliterator spliterator,
IntFunction generator);
}
}