1 /*
2  * Copyright (c) 2012, 2020, Oracle and/or its affiliates. All rights reserved.
3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4  *
5  * This code is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License version 2 only, as
7  * published by the Free Software Foundation.  Oracle designates this
8  * particular file as subject to the "Classpath" exception as provided
9  * by Oracle in the LICENSE file that accompanied this code.
10  *
11  * This code is distributed in the hope that it will be useful, but WITHOUT
12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14  * version 2 for more details (a copy is included in the LICENSE file that
15  * accompanied this code).
16  *
17  * You should have received a copy of the GNU General Public License version
18  * 2 along with this work; if not, write to the Free Software Foundation,
19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20  *
21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22  * or visit www.oracle.com if you need additional information or have any
23  * questions.
24  */
25 package java.util.stream;
26 
27 import java.util.ArrayList;
28 import java.util.Arrays;
29 import java.util.Comparator;
30 import java.util.Iterator;
31 import java.util.List;
32 import java.util.Objects;
33 import java.util.Optional;
34 import java.util.Spliterator;
35 import java.util.Spliterators;
36 import java.util.function.BiConsumer;
37 import java.util.function.BiFunction;
38 import java.util.function.BinaryOperator;
39 import java.util.function.Consumer;
40 import java.util.function.DoubleConsumer;
41 import java.util.function.Function;
42 import java.util.function.IntConsumer;
43 import java.util.function.IntFunction;
44 import java.util.function.LongConsumer;
45 import java.util.function.Predicate;
46 import java.util.function.Supplier;
47 import java.util.function.ToDoubleFunction;
48 import java.util.function.ToIntFunction;
49 import java.util.function.ToLongFunction;
50 import jdk.internal.access.SharedSecrets;
51 
52 /**
53  * Abstract base class for an intermediate pipeline stage or pipeline source
54  * stage implementing whose elements are of type {@code U}.
55  *
56  * @param <P_IN> type of elements in the upstream source
57  * @param <P_OUT> type of elements in produced by this stage
58  *
59  * @since 1.8
60  * @hide Visible for CTS testing only (OpenJDK8 tests).
61  */
62 // Android-changed: Made public for CTS tests only.
63 public abstract class ReferencePipeline<P_IN, P_OUT>
64         extends AbstractPipeline<P_IN, P_OUT, Stream<P_OUT>>
65         implements Stream<P_OUT>  {
66 
67     /**
68      * Constructor for the head of a stream pipeline.
69      *
70      * @param source {@code Supplier<Spliterator>} describing the stream source
71      * @param sourceFlags the source flags for the stream source, described in
72      *        {@link StreamOpFlag}
73      * @param parallel {@code true} if the pipeline is parallel
74      */
ReferencePipeline(Supplier<? extends Spliterator<?>> source, int sourceFlags, boolean parallel)75     ReferencePipeline(Supplier<? extends Spliterator<?>> source,
76                       int sourceFlags, boolean parallel) {
77         super(source, sourceFlags, parallel);
78     }
79 
80     /**
81      * Constructor for the head of a stream pipeline.
82      *
83      * @param source {@code Spliterator} describing the stream source
84      * @param sourceFlags The source flags for the stream source, described in
85      *        {@link StreamOpFlag}
86      * @param parallel {@code true} if the pipeline is parallel
87      */
ReferencePipeline(Spliterator<?> source, int sourceFlags, boolean parallel)88     ReferencePipeline(Spliterator<?> source,
89                       int sourceFlags, boolean parallel) {
90         super(source, sourceFlags, parallel);
91     }
92 
93     /**
94      * Constructor for appending an intermediate operation onto an existing
95      * pipeline.
96      *
97      * @param upstream the upstream element source.
98      */
ReferencePipeline(AbstractPipeline<?, P_IN, ?> upstream, int opFlags)99     ReferencePipeline(AbstractPipeline<?, P_IN, ?> upstream, int opFlags) {
100         super(upstream, opFlags);
101     }
102 
103     // Shape-specific methods
104 
105     @Override
106     // Android-changed: Make public, to match the method it's overriding.
getOutputShape()107     public final StreamShape getOutputShape() {
108         return StreamShape.REFERENCE;
109     }
110 
111     @Override
112     // Android-changed: Make public, to match the method it's overriding.
evaluateToNode(PipelineHelper<P_OUT> helper, Spliterator<P_IN> spliterator, boolean flattenTree, IntFunction<P_OUT[]> generator)113     public final <P_IN> Node<P_OUT> evaluateToNode(PipelineHelper<P_OUT> helper,
114                                         Spliterator<P_IN> spliterator,
115                                         boolean flattenTree,
116                                         IntFunction<P_OUT[]> generator) {
117         return Nodes.collect(helper, spliterator, flattenTree, generator);
118     }
119 
120     @Override
121     // Android-changed: Make public, to match the method it's overriding.
wrap(PipelineHelper<P_OUT> ph, Supplier<Spliterator<P_IN>> supplier, boolean isParallel)122     public final <P_IN> Spliterator<P_OUT> wrap(PipelineHelper<P_OUT> ph,
123                                      Supplier<Spliterator<P_IN>> supplier,
124                                      boolean isParallel) {
125         return new StreamSpliterators.WrappingSpliterator<>(ph, supplier, isParallel);
126     }
127 
128     @Override
129     // Android-changed: Make public, to match the method it's overriding.
lazySpliterator(Supplier<? extends Spliterator<P_OUT>> supplier)130     public final Spliterator<P_OUT> lazySpliterator(Supplier<? extends Spliterator<P_OUT>> supplier) {
131         return new StreamSpliterators.DelegatingSpliterator<>(supplier);
132     }
133 
134     @Override
135     // Android-changed: Make public, to match the method it's overriding.
forEachWithCancel(Spliterator<P_OUT> spliterator, Sink<P_OUT> sink)136     public final boolean forEachWithCancel(Spliterator<P_OUT> spliterator, Sink<P_OUT> sink) {
137         boolean cancelled;
138         do { } while (!(cancelled = sink.cancellationRequested()) && spliterator.tryAdvance(sink));
139         return cancelled;
140     }
141 
142     @Override
143     // Android-changed: Make public, to match the method it's overriding.
makeNodeBuilder(long exactSizeIfKnown, IntFunction<P_OUT[]> generator)144     public final Node.Builder<P_OUT> makeNodeBuilder(long exactSizeIfKnown, IntFunction<P_OUT[]> generator) {
145         return Nodes.builder(exactSizeIfKnown, generator);
146     }
147 
148 
149     // BaseStream
150 
151     @Override
iterator()152     public final Iterator<P_OUT> iterator() {
153         return Spliterators.iterator(spliterator());
154     }
155 
156 
157     // Stream
158 
159     // Stateless intermediate operations from Stream
160 
161     @Override
unordered()162     public Stream<P_OUT> unordered() {
163         if (!isOrdered())
164             return this;
165         return new StatelessOp<P_OUT, P_OUT>(this, StreamShape.REFERENCE, StreamOpFlag.NOT_ORDERED) {
166             @Override
167             // Android-changed: Make public, to match the method it's overriding.
168             public Sink<P_OUT> opWrapSink(int flags, Sink<P_OUT> sink) {
169                 return sink;
170             }
171         };
172     }
173 
174     @Override
175     public final Stream<P_OUT> filter(Predicate<? super P_OUT> predicate) {
176         Objects.requireNonNull(predicate);
177         return new StatelessOp<P_OUT, P_OUT>(this, StreamShape.REFERENCE,
178                                      StreamOpFlag.NOT_SIZED) {
179             @Override
180             // Android-changed: Make public, to match the method it's overriding.
181             public Sink<P_OUT> opWrapSink(int flags, Sink<P_OUT> sink) {
182                 return new Sink.ChainedReference<P_OUT, P_OUT>(sink) {
183                     @Override
184                     public void begin(long size) {
185                         downstream.begin(-1);
186                     }
187 
188                     @Override
189                     public void accept(P_OUT u) {
190                         if (predicate.test(u))
191                             downstream.accept(u);
192                     }
193                 };
194             }
195         };
196     }
197 
198     @Override
199     @SuppressWarnings("unchecked")
200     public final <R> Stream<R> map(Function<? super P_OUT, ? extends R> mapper) {
201         Objects.requireNonNull(mapper);
202         return new StatelessOp<P_OUT, R>(this, StreamShape.REFERENCE,
203                                      StreamOpFlag.NOT_SORTED | StreamOpFlag.NOT_DISTINCT) {
204             @Override
205             public Sink<P_OUT> opWrapSink(int flags, Sink<R> sink) {
206                 return new Sink.ChainedReference<P_OUT, R>(sink) {
207                     @Override
208                     public void accept(P_OUT u) {
209                         downstream.accept(mapper.apply(u));
210                     }
211                 };
212             }
213         };
214     }
215 
216     @Override
217     public final IntStream mapToInt(ToIntFunction<? super P_OUT> mapper) {
218         Objects.requireNonNull(mapper);
219         return new IntPipeline.StatelessOp<P_OUT>(this, StreamShape.REFERENCE,
220                                               StreamOpFlag.NOT_SORTED | StreamOpFlag.NOT_DISTINCT) {
221             @Override
222             // Android-changed: Make public, to match the method it's overriding.
223             public Sink<P_OUT> opWrapSink(int flags, Sink<Integer> sink) {
224                 return new Sink.ChainedReference<P_OUT, Integer>(sink) {
225                     @Override
226                     public void accept(P_OUT u) {
227                         downstream.accept(mapper.applyAsInt(u));
228                     }
229                 };
230             }
231         };
232     }
233 
234     @Override
235     public final LongStream mapToLong(ToLongFunction<? super P_OUT> mapper) {
236         Objects.requireNonNull(mapper);
237         return new LongPipeline.StatelessOp<P_OUT>(this, StreamShape.REFERENCE,
238                                       StreamOpFlag.NOT_SORTED | StreamOpFlag.NOT_DISTINCT) {
239             @Override
240             // Android-changed: Make public, to match the method it's overriding.
241             public Sink<P_OUT> opWrapSink(int flags, Sink<Long> sink) {
242                 return new Sink.ChainedReference<P_OUT, Long>(sink) {
243                     @Override
244                     public void accept(P_OUT u) {
245                         downstream.accept(mapper.applyAsLong(u));
246                     }
247                 };
248             }
249         };
250     }
251 
252     @Override
253     public final DoubleStream mapToDouble(ToDoubleFunction<? super P_OUT> mapper) {
254         Objects.requireNonNull(mapper);
255         return new DoublePipeline.StatelessOp<P_OUT>(this, StreamShape.REFERENCE,
256                                         StreamOpFlag.NOT_SORTED | StreamOpFlag.NOT_DISTINCT) {
257             @Override
258             // Android-changed: Make public, to match the method it's overriding.
259             public Sink<P_OUT> opWrapSink(int flags, Sink<Double> sink) {
260                 return new Sink.ChainedReference<P_OUT, Double>(sink) {
261                     @Override
262                     public void accept(P_OUT u) {
263                         downstream.accept(mapper.applyAsDouble(u));
264                     }
265                 };
266             }
267         };
268     }
269 
270     @Override
271     public final <R> Stream<R> flatMap(Function<? super P_OUT, ? extends Stream<? extends R>> mapper) {
272         Objects.requireNonNull(mapper);
273         return new StatelessOp<P_OUT, R>(this, StreamShape.REFERENCE,
274                                      StreamOpFlag.NOT_SORTED | StreamOpFlag.NOT_DISTINCT | StreamOpFlag.NOT_SIZED) {
275             @Override
276             public Sink<P_OUT> opWrapSink(int flags, Sink<R> sink) {
277                 return new Sink.ChainedReference<>(sink) {
278                     // true if cancellationRequested() has been called
279                     boolean cancellationRequestedCalled;
280 
281                     @Override
282                     public void begin(long size) {
283                         downstream.begin(-1);
284                     }
285 
286                     @Override
287                     public void accept(P_OUT u) {
288                         try (Stream<? extends R> result = mapper.apply(u)) {
289                             if (result != null) {
290                                 if (!cancellationRequestedCalled) {
291                                     result.sequential().forEach(downstream);
292                                 }
293                                 else {
294                                     var s = result.sequential().spliterator();
295                                     do { } while (!downstream.cancellationRequested() && s.tryAdvance(downstream));
296                                 }
297                             }
298                         }
299                     }
300 
301                     @Override
302                     public boolean cancellationRequested() {
303                         // If this method is called then an operation within the stream
304                         // pipeline is short-circuiting (see AbstractPipeline.copyInto).
305                         // Note that we cannot differentiate between an upstream or
306                         // downstream operation
307                         cancellationRequestedCalled = true;
308                         return downstream.cancellationRequested();
309                     }
310                 };
311             }
312         };
313     }
314 
315     @Override
316     public final IntStream flatMapToInt(Function<? super P_OUT, ? extends IntStream> mapper) {
317         Objects.requireNonNull(mapper);
318         return new IntPipeline.StatelessOp<P_OUT>(this, StreamShape.REFERENCE,
319                                               StreamOpFlag.NOT_SORTED | StreamOpFlag.NOT_DISTINCT | StreamOpFlag.NOT_SIZED) {
320             @Override
321             // Android-changed: Make public, to match the method it's overriding.
322             public Sink<P_OUT> opWrapSink(int flags, Sink<Integer> sink) {
323                 return new Sink.ChainedReference<P_OUT, Integer>(sink) {
324                     // true if cancellationRequested() has been called
325                     boolean cancellationRequestedCalled;
326 
327                     // cache the consumer to avoid creation on every accepted element
328                     IntConsumer downstreamAsInt = downstream::accept;
329 
330                     @Override
331                     public void begin(long size) {
332                         downstream.begin(-1);
333                     }
334 
335                     @Override
336                     public void accept(P_OUT u) {
337                         try (IntStream result = mapper.apply(u)) {
338                             if (result != null) {
339                                 if (!cancellationRequestedCalled) {
340                                     result.sequential().forEach(downstreamAsInt);
341                                 }
342                                 else {
343                                     var s = result.sequential().spliterator();
344                                     do { } while (!downstream.cancellationRequested() && s.tryAdvance(downstreamAsInt));
345                                 }
346                             }
347                         }
348                     }
349 
350                     @Override
351                     public boolean cancellationRequested() {
352                         cancellationRequestedCalled = true;
353                         return downstream.cancellationRequested();
354                     }
355                 };
356             }
357         };
358     }
359 
360     @Override
361     public final DoubleStream flatMapToDouble(Function<? super P_OUT, ? extends DoubleStream> mapper) {
362         Objects.requireNonNull(mapper);
363         return new DoublePipeline.StatelessOp<P_OUT>(this, StreamShape.REFERENCE,
364                                                      StreamOpFlag.NOT_SORTED | StreamOpFlag.NOT_DISTINCT | StreamOpFlag.NOT_SIZED) {
365             @Override
366             // Android-changed: Make public, to match the method it's overriding.
367             public Sink<P_OUT> opWrapSink(int flags, Sink<Double> sink) {
368                 return new Sink.ChainedReference<P_OUT, Double>(sink) {
369                     // true if cancellationRequested() has been called
370                     boolean cancellationRequestedCalled;
371 
372                     // cache the consumer to avoid creation on every accepted element
373                     DoubleConsumer downstreamAsDouble = downstream::accept;
374 
375                     @Override
376                     public void begin(long size) {
377                         downstream.begin(-1);
378                     }
379 
380                     @Override
381                     public void accept(P_OUT u) {
382                         try (DoubleStream result = mapper.apply(u)) {
383                             if (result != null) {
384                                 if (!cancellationRequestedCalled) {
385                                     result.sequential().forEach(downstreamAsDouble);
386                                 }
387                                 else {
388                                     var s = result.sequential().spliterator();
389                                     do { } while (!downstream.cancellationRequested() && s.tryAdvance(downstreamAsDouble));
390                                 }
391                             }
392                         }
393                     }
394 
395                     @Override
396                     public boolean cancellationRequested() {
397                         cancellationRequestedCalled = true;
398                         return downstream.cancellationRequested();
399                     }
400                 };
401             }
402         };
403     }
404 
405     @Override
406     public final LongStream flatMapToLong(Function<? super P_OUT, ? extends LongStream> mapper) {
407         Objects.requireNonNull(mapper);
408         // We can do better than this, by polling cancellationRequested when stream is infinite
409         return new LongPipeline.StatelessOp<P_OUT>(this, StreamShape.REFERENCE,
410                                                    StreamOpFlag.NOT_SORTED | StreamOpFlag.NOT_DISTINCT | StreamOpFlag.NOT_SIZED) {
411             @Override
412             // Android-changed: Make public, to match the method it's overriding.
413             public Sink<P_OUT> opWrapSink(int flags, Sink<Long> sink) {
414                 return new Sink.ChainedReference<P_OUT, Long>(sink) {
415                     // true if cancellationRequested() has been called
416                     boolean cancellationRequestedCalled;
417 
418                     // cache the consumer to avoid creation on every accepted element
419                     LongConsumer downstreamAsLong = downstream::accept;
420 
421                     @Override
422                     public void begin(long size) {
423                         downstream.begin(-1);
424                     }
425 
426                     @Override
427                     public void accept(P_OUT u) {
428                         try (LongStream result = mapper.apply(u)) {
429                             if (result != null) {
430                                 if (!cancellationRequestedCalled) {
431                                     result.sequential().forEach(downstreamAsLong);
432                                 }
433                                 else {
434                                     var s = result.sequential().spliterator();
435                                     do { } while (!downstream.cancellationRequested() && s.tryAdvance(downstreamAsLong));
436                                 }
437                             }
438                         }
439                     }
440 
441                     @Override
442                     public boolean cancellationRequested() {
443                         cancellationRequestedCalled = true;
444                         return downstream.cancellationRequested();
445                     }
446                 };
447             }
448         };
449     }
450 
451     @Override
452     public final <R> Stream<R> mapMulti(BiConsumer<? super P_OUT, ? super Consumer<R>> mapper) {
453         Objects.requireNonNull(mapper);
454         return new StatelessOp<>(this, StreamShape.REFERENCE,
455                 StreamOpFlag.NOT_SORTED | StreamOpFlag.NOT_DISTINCT | StreamOpFlag.NOT_SIZED) {
456             @Override
457             // Android-changed: Make public, to match the method it's overriding.
458             public Sink<P_OUT> opWrapSink(int flags, Sink<R> sink) {
459                 return new Sink.ChainedReference<>(sink) {
460 
461                     @Override
462                     public void begin(long size) {
463                         downstream.begin(-1);
464                     }
465 
466                     @Override
467                     @SuppressWarnings("unchecked")
468                     public void accept(P_OUT u) {
469                         mapper.accept(u, (Consumer<R>) downstream);
470                     }
471                 };
472             }
473         };
474     }
475 
476     @Override
477     public final IntStream mapMultiToInt(BiConsumer<? super P_OUT, ? super IntConsumer> mapper) {
478         Objects.requireNonNull(mapper);
479         return new IntPipeline.StatelessOp<>(this, StreamShape.REFERENCE,
480                 StreamOpFlag.NOT_SORTED | StreamOpFlag.NOT_DISTINCT | StreamOpFlag.NOT_SIZED) {
481             @Override
482             // Android-changed: Make public, to match the method it's overriding.
483             public Sink<P_OUT> opWrapSink(int flags, Sink<Integer> sink) {
484                 return new Sink.ChainedReference<>(sink) {
485 
486                     @Override
487                     public void begin(long size) {
488                         downstream.begin(-1);
489                     }
490 
491                     @Override
492                     @SuppressWarnings("unchecked")
493                     public void accept(P_OUT u) {
494                         mapper.accept(u, (IntConsumer)downstream);
495                     }
496                 };
497             }
498         };
499     }
500 
501     @Override
502     public final LongStream mapMultiToLong(BiConsumer<? super P_OUT, ? super LongConsumer> mapper) {
503         Objects.requireNonNull(mapper);
504         return new LongPipeline.StatelessOp<>(this, StreamShape.REFERENCE,
505                 StreamOpFlag.NOT_SORTED | StreamOpFlag.NOT_DISTINCT | StreamOpFlag.NOT_SIZED) {
506             @Override
507             // Android-changed: Make public, to match the method it's overriding.
508             public Sink<P_OUT> opWrapSink(int flags, Sink<Long> sink) {
509                 return new Sink.ChainedReference<>(sink) {
510 
511                     @Override
512                     public void begin(long size) {
513                         downstream.begin(-1);
514                     }
515 
516                     @Override
517                     @SuppressWarnings("unchecked")
518                     public void accept(P_OUT u) {
519                         mapper.accept(u, (LongConsumer) downstream);
520                     }
521                 };
522             }
523         };
524     }
525 
526 
527     @Override
528     public final DoubleStream mapMultiToDouble(BiConsumer<? super P_OUT, ? super DoubleConsumer> mapper) {
529         Objects.requireNonNull(mapper);
530         return new DoublePipeline.StatelessOp<>(this, StreamShape.REFERENCE,
531                 StreamOpFlag.NOT_SORTED | StreamOpFlag.NOT_DISTINCT | StreamOpFlag.NOT_SIZED) {
532             @Override
533             // Android-changed: Make public, to match the method it's overriding.
534             public Sink<P_OUT> opWrapSink(int flags, Sink<Double> sink) {
535                 return new Sink.ChainedReference<>(sink) {
536 
537                     @Override
538                     public void begin(long size) {
539                         downstream.begin(-1);
540                     }
541 
542                     @Override
543                     @SuppressWarnings("unchecked")
544                     public void accept(P_OUT u) {
545                         mapper.accept(u, (DoubleConsumer) downstream);
546                     }
547                 };
548             }
549         };
550     }
551 
552     @Override
553     public final Stream<P_OUT> peek(Consumer<? super P_OUT> action) {
554         Objects.requireNonNull(action);
555         return new StatelessOp<P_OUT, P_OUT>(this, StreamShape.REFERENCE,
556                                      0) {
557             @Override
558             // Android-changed: Make public, to match the method it's overriding.
559             public Sink<P_OUT> opWrapSink(int flags, Sink<P_OUT> sink) {
560                 return new Sink.ChainedReference<P_OUT, P_OUT>(sink) {
561                     @Override
562                     public void accept(P_OUT u) {
563                         action.accept(u);
564                         downstream.accept(u);
565                     }
566                 };
567             }
568         };
569     }
570 
571     // Stateful intermediate operations from Stream
572 
573     @Override
574     public final Stream<P_OUT> distinct() {
575         return DistinctOps.makeRef(this);
576     }
577 
578     @Override
579     public final Stream<P_OUT> sorted() {
580         return SortedOps.makeRef(this);
581     }
582 
583     @Override
584     public final Stream<P_OUT> sorted(Comparator<? super P_OUT> comparator) {
585         return SortedOps.makeRef(this, comparator);
586     }
587 
588     @Override
589     public final Stream<P_OUT> limit(long maxSize) {
590         if (maxSize < 0)
591             throw new IllegalArgumentException(Long.toString(maxSize));
592         return SliceOps.makeRef(this, 0, maxSize);
593     }
594 
595     @Override
596     public final Stream<P_OUT> skip(long n) {
597         if (n < 0)
598             throw new IllegalArgumentException(Long.toString(n));
599         if (n == 0)
600             return this;
601         else
602             return SliceOps.makeRef(this, n, -1);
603     }
604 
605     @Override
606     public final Stream<P_OUT> takeWhile(Predicate<? super P_OUT> predicate) {
607         return WhileOps.makeTakeWhileRef(this, predicate);
608     }
609 
610     @Override
611     public final Stream<P_OUT> dropWhile(Predicate<? super P_OUT> predicate) {
612         return WhileOps.makeDropWhileRef(this, predicate);
613     }
614 
615     // Terminal operations from Stream
616 
617     @Override
618     public void forEach(Consumer<? super P_OUT> action) {
619         evaluate(ForEachOps.makeRef(action, false));
620     }
621 
622     @Override
623     public void forEachOrdered(Consumer<? super P_OUT> action) {
624         evaluate(ForEachOps.makeRef(action, true));
625     }
626 
627     @Override
628     @SuppressWarnings("unchecked")
629     public final <A> A[] toArray(IntFunction<A[]> generator) {
630         // Since A has no relation to U (not possible to declare that A is an upper bound of U)
631         // there will be no static type checking.
632         // Therefore use a raw type and assume A == U rather than propagating the separation of A and U
633         // throughout the code-base.
634         // The runtime type of U is never checked for equality with the component type of the runtime type of A[].
635         // Runtime checking will be performed when an element is stored in A[], thus if A is not a
636         // super type of U an ArrayStoreException will be thrown.
637         @SuppressWarnings("rawtypes")
638         IntFunction rawGenerator = (IntFunction) generator;
639         // Android-changed: Eclipse compiler requires explicit (Node<A[]>) cast (b/29399275).
640         return (A[]) Nodes.flatten((Node<A[]>) evaluateToArrayNode(rawGenerator), rawGenerator)
641                 .asArray(rawGenerator);
642     }
643 
644     @Override
645     public final Object[] toArray() {
646         return toArray(Object[]::new);
647     }
648 
649     @Override
650     public List<P_OUT> toList() {
651         return SharedSecrets.getJavaUtilCollectionAccess().listFromTrustedArrayNullsAllowed(this.toArray());
652     }
653 
654     @Override
655     public final boolean anyMatch(Predicate<? super P_OUT> predicate) {
656         return evaluate(MatchOps.makeRef(predicate, MatchOps.MatchKind.ANY));
657     }
658 
659     @Override
660     public final boolean allMatch(Predicate<? super P_OUT> predicate) {
661         return evaluate(MatchOps.makeRef(predicate, MatchOps.MatchKind.ALL));
662     }
663 
664     @Override
665     public final boolean noneMatch(Predicate<? super P_OUT> predicate) {
666         return evaluate(MatchOps.makeRef(predicate, MatchOps.MatchKind.NONE));
667     }
668 
669     @Override
670     public final Optional<P_OUT> findFirst() {
671         return evaluate(FindOps.makeRef(true));
672     }
673 
674     @Override
675     public final Optional<P_OUT> findAny() {
676         return evaluate(FindOps.makeRef(false));
677     }
678 
679     @Override
680     public final P_OUT reduce(final P_OUT identity, final BinaryOperator<P_OUT> accumulator) {
681         return evaluate(ReduceOps.makeRef(identity, accumulator, accumulator));
682     }
683 
684     @Override
685     public final Optional<P_OUT> reduce(BinaryOperator<P_OUT> accumulator) {
686         return evaluate(ReduceOps.makeRef(accumulator));
687     }
688 
689     @Override
690     public final <R> R reduce(R identity, BiFunction<R, ? super P_OUT, R> accumulator, BinaryOperator<R> combiner) {
691         return evaluate(ReduceOps.makeRef(identity, accumulator, combiner));
692     }
693 
694     @Override
695     @SuppressWarnings("unchecked")
696     public final <R, A> R collect(Collector<? super P_OUT, A, R> collector) {
697         A container;
698         if (isParallel()
699                 && (collector.characteristics().contains(Collector.Characteristics.CONCURRENT))
700                 && (!isOrdered() || collector.characteristics().contains(Collector.Characteristics.UNORDERED))) {
701             container = collector.supplier().get();
702             BiConsumer<A, ? super P_OUT> accumulator = collector.accumulator();
703             forEach(u -> accumulator.accept(container, u));
704         }
705         else {
706             container = evaluate(ReduceOps.makeRef(collector));
707         }
708         return collector.characteristics().contains(Collector.Characteristics.IDENTITY_FINISH)
709                ? (R) container
710                : collector.finisher().apply(container);
711     }
712 
713     @Override
714     public final <R> R collect(Supplier<R> supplier,
715                                BiConsumer<R, ? super P_OUT> accumulator,
716                                BiConsumer<R, R> combiner) {
717         return evaluate(ReduceOps.makeRef(supplier, accumulator, combiner));
718     }
719 
720     @Override
721     public final Optional<P_OUT> max(Comparator<? super P_OUT> comparator) {
722         return reduce(BinaryOperator.maxBy(comparator));
723     }
724 
725     @Override
726     public final Optional<P_OUT> min(Comparator<? super P_OUT> comparator) {
727         return reduce(BinaryOperator.minBy(comparator));
728 
729     }
730 
731     @Override
732     public final long count() {
733         return evaluate(ReduceOps.makeRefCounting());
734     }
735 
736     //
737 
738     /**
739      * Source stage of a ReferencePipeline.
740      *
741      * @param <E_IN> type of elements in the upstream source
742      * @param <E_OUT> type of elements in produced by this stage
743      * @since 1.8
744      * @hide Visible for CTS testing only (OpenJDK8 tests).
745      */
746     // Android-changed: Made public for CTS tests only.
747     public static class Head<E_IN, E_OUT> extends ReferencePipeline<E_IN, E_OUT> {
748         /**
749          * Constructor for the source stage of a Stream.
750          *
751          * @param source {@code Supplier<Spliterator>} describing the stream
752          *               source
753          * @param sourceFlags the source flags for the stream source, described
754          *                    in {@link StreamOpFlag}
755          */
756         // Android-changed: Made public for CTS tests only.
757         public Head(Supplier<? extends Spliterator<?>> source,
758              int sourceFlags, boolean parallel) {
759             super(source, sourceFlags, parallel);
760         }
761 
762         /**
763          * Constructor for the source stage of a Stream.
764          *
765          * @param source {@code Spliterator} describing the stream source
766          * @param sourceFlags the source flags for the stream source, described
767          *                    in {@link StreamOpFlag}
768          */
769         // Android-changed: Made public for CTS tests only.
770         public Head(Spliterator<?> source,
771              int sourceFlags, boolean parallel) {
772             super(source, sourceFlags, parallel);
773         }
774 
775         @Override
776         // Android-changed: Make public, to match the method it's overriding.
777         public final boolean opIsStateful() {
778             throw new UnsupportedOperationException();
779         }
780 
781         @Override
782         // Android-changed: Make public, to match the method it's overriding.
783         public final Sink<E_IN> opWrapSink(int flags, Sink<E_OUT> sink) {
784             throw new UnsupportedOperationException();
785         }
786 
787         // Optimized sequential terminal operations for the head of the pipeline
788 
789         @Override
790         public void forEach(Consumer<? super E_OUT> action) {
791             if (!isParallel()) {
792                 sourceStageSpliterator().forEachRemaining(action);
793             }
794             else {
795                 super.forEach(action);
796             }
797         }
798 
799         @Override
800         public void forEachOrdered(Consumer<? super E_OUT> action) {
801             if (!isParallel()) {
802                 sourceStageSpliterator().forEachRemaining(action);
803             }
804             else {
805                 super.forEachOrdered(action);
806             }
807         }
808     }
809 
810     /**
811      * Base class for a stateless intermediate stage of a Stream.
812      *
813      * @param <E_IN> type of elements in the upstream source
814      * @param <E_OUT> type of elements in produced by this stage
815      * @since 1.8
816      * @hide Visible for CTS testing only (OpenJDK8 tests).
817      */
818     // Android-changed: Made public for CTS tests only.
819     public abstract static class StatelessOp<E_IN, E_OUT>
820             extends ReferencePipeline<E_IN, E_OUT> {
821         /**
822          * Construct a new Stream by appending a stateless intermediate
823          * operation to an existing stream.
824          *
825          * @param upstream The upstream pipeline stage
826          * @param inputShape The stream shape for the upstream pipeline stage
827          * @param opFlags Operation flags for the new stage
828          */
829         // Android-changed: Made public for CTS tests only.
830         public StatelessOp(AbstractPipeline<?, E_IN, ?> upstream,
831                     StreamShape inputShape,
832                     int opFlags) {
833             super(upstream, opFlags);
834             assert upstream.getOutputShape() == inputShape;
835         }
836 
837         @Override
838         // Android-changed: Make public, to match the method it's overriding.
839         public final boolean opIsStateful() {
840             return false;
841         }
842     }
843 
844     /**
845      * Base class for a stateful intermediate stage of a Stream.
846      *
847      * @param <E_IN> type of elements in the upstream source
848      * @param <E_OUT> type of elements in produced by this stage
849      * @since 1.8
850      * @hide Visible for CTS testing only (OpenJDK8 tests).
851      */
852     // Android-changed: Made public for CTS tests only.
853     public abstract static class StatefulOp<E_IN, E_OUT>
854             extends ReferencePipeline<E_IN, E_OUT> {
855         /**
856          * Construct a new Stream by appending a stateful intermediate operation
857          * to an existing stream.
858          * @param upstream The upstream pipeline stage
859          * @param inputShape The stream shape for the upstream pipeline stage
860          * @param opFlags Operation flags for the new stage
861          */
862         // Android-changed: Made public for CTS tests only.
863         public StatefulOp(AbstractPipeline<?, E_IN, ?> upstream,
864                    StreamShape inputShape,
865                    int opFlags) {
866             super(upstream, opFlags);
867             assert upstream.getOutputShape() == inputShape;
868         }
869 
870         @Override
871         // Android-changed: Make public, to match the method it's overriding.
872         public final boolean opIsStateful() {
873             return true;
874         }
875 
876         @Override
877         // Android-changed: Make public, to match the method it's overriding.
878         public abstract <P_IN> Node<E_OUT> opEvaluateParallel(PipelineHelper<E_OUT> helper,
879                                                        Spliterator<P_IN> spliterator,
880                                                        IntFunction<E_OUT[]> generator);
881     }
882 }
883