rev 53930 : 8148917: enhanced-for statement should allow streams
Reviewed-by: XXX

   1 /*
   2  * Copyright (c) 2012, 2019, 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.nio.file.Files;
  28 import java.nio.file.Path;
  29 import java.util.Arrays;
  30 import java.util.Collection;
  31 import java.util.Comparator;
  32 import java.util.Objects;
  33 import java.util.Optional;
  34 import java.util.Spliterator;
  35 import java.util.Spliterators;
  36 import java.util.concurrent.ConcurrentHashMap;
  37 import java.util.function.BiConsumer;
  38 import java.util.function.BiFunction;
  39 import java.util.function.BinaryOperator;
  40 import java.util.function.Consumer;
  41 import java.util.function.Function;
  42 import java.util.function.IntFunction;
  43 import java.util.function.Predicate;
  44 import java.util.function.Supplier;
  45 import java.util.function.ToDoubleFunction;
  46 import java.util.function.ToIntFunction;
  47 import java.util.function.ToLongFunction;
  48 import java.util.function.UnaryOperator;
  49 
  50 /**
  51  * A sequence of elements supporting sequential and parallel aggregate
  52  * operations.  The following example illustrates an aggregate operation using
  53  * {@link Stream} and {@link IntStream}:
  54  *
  55  * <pre>{@code
  56  *     int sum = widgets.stream()
  57  *                      .filter(w -> w.getColor() == RED)
  58  *                      .mapToInt(w -> w.getWeight())
  59  *                      .sum();
  60  * }</pre>
  61  *
  62  * In this example, {@code widgets} is a {@code Collection<Widget>}.  We create
  63  * a stream of {@code Widget} objects via {@link Collection#stream Collection.stream()},
  64  * filter it to produce a stream containing only the red widgets, and then
  65  * transform it into a stream of {@code int} values representing the weight of
  66  * each red widget. Then this stream is summed to produce a total weight.
  67  *
  68  * <p>In addition to {@code Stream}, which is a stream of object references,
  69  * there are primitive specializations for {@link IntStream}, {@link LongStream},
  70  * and {@link DoubleStream}, all of which are referred to as "streams" and
  71  * conform to the characteristics and restrictions described here.
  72  *
  73  * <p>To perform a computation, stream
  74  * <a href="package-summary.html#StreamOps">operations</a> are composed into a
  75  * <em>stream pipeline</em>.  A stream pipeline consists of a source (which
  76  * might be an array, a collection, a generator function, an I/O channel,
  77  * etc), zero or more <em>intermediate operations</em> (which transform a
  78  * stream into another stream, such as {@link Stream#filter(Predicate)}), and a
  79  * <em>terminal operation</em> (which produces a result or side-effect, such
  80  * as {@link Stream#count()} or {@link Stream#forEach(Consumer)}).
  81  * Streams are lazy; computation on the source data is only performed when the
  82  * terminal operation is initiated, and source elements are consumed only
  83  * as needed.
  84  *
  85  * <p>A stream implementation is permitted significant latitude in optimizing
  86  * the computation of the result.  For example, a stream implementation is free
  87  * to elide operations (or entire stages) from a stream pipeline -- and
  88  * therefore elide invocation of behavioral parameters -- if it can prove that
  89  * it would not affect the result of the computation.  This means that
  90  * side-effects of behavioral parameters may not always be executed and should
  91  * not be relied upon, unless otherwise specified (such as by the terminal
  92  * operations {@code forEach} and {@code forEachOrdered}). (For a specific
  93  * example of such an optimization, see the API note documented on the
  94  * {@link #count} operation.  For more detail, see the
  95  * <a href="package-summary.html#SideEffects">side-effects</a> section of the
  96  * stream package documentation.)
  97  *
  98  * <p>Collections and streams, while bearing some superficial similarities,
  99  * have different goals.  Collections are primarily concerned with the efficient
 100  * management of, and access to, their elements.  By contrast, streams do not
 101  * provide a means to directly access or manipulate their elements, and are
 102  * instead concerned with declaratively describing their source and the
 103  * computational operations which will be performed in aggregate on that source.
 104  * However, if the provided stream operations do not offer the desired
 105  * functionality, the {@link #iterator()} and {@link #spliterator()} operations
 106  * can be used to perform a controlled traversal. Stream implements the
 107  * {@link IterableOnce} interface, allowing a stream instance to be used
 108  * in an enhanced-for ("for each") statement. Note that this statement implicitly
 109  * calls the {@code iterator()} method, which consumes the stream. The stream
 110  * thus cannot be used for any subsequent operations.
 111  *
 112  * <p>A stream pipeline, like the "widgets" example above, can be viewed as
 113  * a <em>query</em> on the stream source.  Unless the source was explicitly
 114  * designed for concurrent modification (such as a {@link ConcurrentHashMap}),
 115  * unpredictable or erroneous behavior may result from modifying the stream
 116  * source while it is being queried.
 117  *
 118  * <p>Most stream operations accept parameters that describe user-specified
 119  * behavior, such as the lambda expression {@code w -> w.getWeight()} passed to
 120  * {@code mapToInt} in the example above.  To preserve correct behavior,
 121  * these <em>behavioral parameters</em>:
 122  * <ul>
 123  * <li>must be <a href="package-summary.html#NonInterference">non-interfering</a>
 124  * (they do not modify the stream source); and</li>
 125  * <li>in most cases must be <a href="package-summary.html#Statelessness">stateless</a>
 126  * (their result should not depend on any state that might change during execution
 127  * of the stream pipeline).</li>
 128  * </ul>
 129  *
 130  * <p>Such parameters are always instances of a
 131  * <a href="../function/package-summary.html">functional interface</a> such
 132  * as {@link java.util.function.Function}, and are often lambda expressions or
 133  * method references.  Unless otherwise specified these parameters must be
 134  * <em>non-null</em>.
 135  *
 136  * <p>A stream should be operated on (invoking an intermediate or terminal stream
 137  * operation) only once.  This rules out, for example, "forked" streams, where
 138  * the same source feeds two or more pipelines, or multiple traversals of the
 139  * same stream.  A stream implementation may throw {@link IllegalStateException}
 140  * if it detects that the stream is being reused. However, since some stream
 141  * operations may return their receiver rather than a new stream object, it may
 142  * not be possible to detect reuse in all cases.
 143  *
 144  * <p>Streams have a {@link #close()} method and implement {@link AutoCloseable}.
 145  * Operating on a stream after it has been closed will throw {@link IllegalStateException}.
 146  * Most stream instances do not actually need to be closed after use, as they
 147  * are backed by collections, arrays, or generating functions, which require no
 148  * special resource management. Generally, only streams whose source is an IO channel,
 149  * such as those returned by {@link Files#lines(Path)}, will require closing. If a
 150  * stream does require closing, it must be opened as a resource within a try-with-resources
 151  * statement or similar control structure to ensure that it is closed promptly after its
 152  * operations have completed.
 153  *
 154  * <p>Stream pipelines may execute either sequentially or in
 155  * <a href="package-summary.html#Parallelism">parallel</a>.  This
 156  * execution mode is a property of the stream.  Streams are created
 157  * with an initial choice of sequential or parallel execution.  (For example,
 158  * {@link Collection#stream() Collection.stream()} creates a sequential stream,
 159  * and {@link Collection#parallelStream() Collection.parallelStream()} creates
 160  * a parallel one.)  This choice of execution mode may be modified by the
 161  * {@link #sequential()} or {@link #parallel()} methods, and may be queried with
 162  * the {@link #isParallel()} method.
 163  *
 164  * @param <T> the type of the stream elements
 165  * @since 1.8
 166  * @see IntStream
 167  * @see LongStream
 168  * @see DoubleStream
 169  * @see <a href="package-summary.html">java.util.stream</a>
 170  */
 171 public interface Stream<T> extends BaseStream<T, Stream<T>>, IterableOnce<T> {
 172 
 173     // Need to re-abstract spliterator() to avoid inheriting the default
 174     // method from Iterable.
 175     /**
 176      * {@inheritDoc}
 177      * @return {@inheritDoc}
 178      */
 179     Spliterator<T> spliterator();
 180 
 181     /**
 182      * Returns a stream consisting of the elements of this stream that match
 183      * the given predicate.
 184      *
 185      * <p>This is an <a href="package-summary.html#StreamOps">intermediate
 186      * operation</a>.
 187      *
 188      * @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>,
 189      *                  <a href="package-summary.html#Statelessness">stateless</a>
 190      *                  predicate to apply to each element to determine if it
 191      *                  should be included
 192      * @return the new stream
 193      */
 194     Stream<T> filter(Predicate<? super T> predicate);
 195 
 196     /**
 197      * Returns a stream consisting of the results of applying the given
 198      * function to the elements of this stream.
 199      *
 200      * <p>This is an <a href="package-summary.html#StreamOps">intermediate
 201      * operation</a>.
 202      *
 203      * @param <R> The element type of the new stream
 204      * @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>,
 205      *               <a href="package-summary.html#Statelessness">stateless</a>
 206      *               function to apply to each element
 207      * @return the new stream
 208      */
 209     <R> Stream<R> map(Function<? super T, ? extends R> mapper);
 210 
 211     /**
 212      * Returns an {@code IntStream} consisting of the results of applying the
 213      * given function to the elements of this stream.
 214      *
 215      * <p>This is an <a href="package-summary.html#StreamOps">
 216      *     intermediate operation</a>.
 217      *
 218      * @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>,
 219      *               <a href="package-summary.html#Statelessness">stateless</a>
 220      *               function to apply to each element
 221      * @return the new stream
 222      */
 223     IntStream mapToInt(ToIntFunction<? super T> mapper);
 224 
 225     /**
 226      * Returns a {@code LongStream} consisting of the results of applying the
 227      * given function to the elements of this stream.
 228      *
 229      * <p>This is an <a href="package-summary.html#StreamOps">intermediate
 230      * operation</a>.
 231      *
 232      * @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>,
 233      *               <a href="package-summary.html#Statelessness">stateless</a>
 234      *               function to apply to each element
 235      * @return the new stream
 236      */
 237     LongStream mapToLong(ToLongFunction<? super T> mapper);
 238 
 239     /**
 240      * Returns a {@code DoubleStream} consisting of the results of applying the
 241      * given function to the elements of this stream.
 242      *
 243      * <p>This is an <a href="package-summary.html#StreamOps">intermediate
 244      * operation</a>.
 245      *
 246      * @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>,
 247      *               <a href="package-summary.html#Statelessness">stateless</a>
 248      *               function to apply to each element
 249      * @return the new stream
 250      */
 251     DoubleStream mapToDouble(ToDoubleFunction<? super T> mapper);
 252 
 253     /**
 254      * Returns a stream consisting of the results of replacing each element of
 255      * this stream with the contents of a mapped stream produced by applying
 256      * the provided mapping function to each element.  Each mapped stream is
 257      * {@link java.util.stream.BaseStream#close() closed} after its contents
 258      * have been placed into this stream.  (If a mapped stream is {@code null}
 259      * an empty stream is used, instead.)
 260      *
 261      * <p>This is an <a href="package-summary.html#StreamOps">intermediate
 262      * operation</a>.
 263      *
 264      * @apiNote
 265      * The {@code flatMap()} operation has the effect of applying a one-to-many
 266      * transformation to the elements of the stream, and then flattening the
 267      * resulting elements into a new stream.
 268      *
 269      * <p><b>Examples.</b>
 270      *
 271      * <p>If {@code orders} is a stream of purchase orders, and each purchase
 272      * order contains a collection of line items, then the following produces a
 273      * stream containing all the line items in all the orders:
 274      * <pre>{@code
 275      *     orders.flatMap(order -> order.getLineItems().stream())...
 276      * }</pre>
 277      *
 278      * <p>If {@code path} is the path to a file, then the following produces a
 279      * stream of the {@code words} contained in that file:
 280      * <pre>{@code
 281      *     Stream<String> lines = Files.lines(path, StandardCharsets.UTF_8);
 282      *     Stream<String> words = lines.flatMap(line -> Stream.of(line.split(" +")));
 283      * }</pre>
 284      * The {@code mapper} function passed to {@code flatMap} splits a line,
 285      * using a simple regular expression, into an array of words, and then
 286      * creates a stream of words from that array.
 287      *
 288      * @param <R> The element type of the new stream
 289      * @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>,
 290      *               <a href="package-summary.html#Statelessness">stateless</a>
 291      *               function to apply to each element which produces a stream
 292      *               of new values
 293      * @return the new stream
 294      */
 295     <R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper);
 296 
 297     /**
 298      * Returns an {@code IntStream} consisting of the results of replacing each
 299      * element of this stream with the contents of a mapped stream produced by
 300      * applying the provided mapping function to each element.  Each mapped
 301      * stream is {@link java.util.stream.BaseStream#close() closed} after its
 302      * contents have been placed into this stream.  (If a mapped stream is
 303      * {@code null} an empty stream is used, instead.)
 304      *
 305      * <p>This is an <a href="package-summary.html#StreamOps">intermediate
 306      * operation</a>.
 307      *
 308      * @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>,
 309      *               <a href="package-summary.html#Statelessness">stateless</a>
 310      *               function to apply to each element which produces a stream
 311      *               of new values
 312      * @return the new stream
 313      * @see #flatMap(Function)
 314      */
 315     IntStream flatMapToInt(Function<? super T, ? extends IntStream> mapper);
 316 
 317     /**
 318      * Returns an {@code LongStream} consisting of the results of replacing each
 319      * element of this stream with the contents of a mapped stream produced by
 320      * applying the provided mapping function to each element.  Each mapped
 321      * stream is {@link java.util.stream.BaseStream#close() closed} after its
 322      * contents have been placed into this stream.  (If a mapped stream is
 323      * {@code null} an empty stream is used, instead.)
 324      *
 325      * <p>This is an <a href="package-summary.html#StreamOps">intermediate
 326      * operation</a>.
 327      *
 328      * @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>,
 329      *               <a href="package-summary.html#Statelessness">stateless</a>
 330      *               function to apply to each element which produces a stream
 331      *               of new values
 332      * @return the new stream
 333      * @see #flatMap(Function)
 334      */
 335     LongStream flatMapToLong(Function<? super T, ? extends LongStream> mapper);
 336 
 337     /**
 338      * Returns an {@code DoubleStream} consisting of the results of replacing
 339      * each element of this stream with the contents of a mapped stream produced
 340      * by applying the provided mapping function to each element.  Each mapped
 341      * stream is {@link java.util.stream.BaseStream#close() closed} after its
 342      * contents have placed been into this stream.  (If a mapped stream is
 343      * {@code null} an empty stream is used, instead.)
 344      *
 345      * <p>This is an <a href="package-summary.html#StreamOps">intermediate
 346      * operation</a>.
 347      *
 348      * @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>,
 349      *               <a href="package-summary.html#Statelessness">stateless</a>
 350      *               function to apply to each element which produces a stream
 351      *               of new values
 352      * @return the new stream
 353      * @see #flatMap(Function)
 354      */
 355     DoubleStream flatMapToDouble(Function<? super T, ? extends DoubleStream> mapper);
 356 
 357     /**
 358      * Returns a stream consisting of the distinct elements (according to
 359      * {@link Object#equals(Object)}) of this stream.
 360      *
 361      * <p>For ordered streams, the selection of distinct elements is stable
 362      * (for duplicated elements, the element appearing first in the encounter
 363      * order is preserved.)  For unordered streams, no stability guarantees
 364      * are made.
 365      *
 366      * <p>This is a <a href="package-summary.html#StreamOps">stateful
 367      * intermediate operation</a>.
 368      *
 369      * @apiNote
 370      * Preserving stability for {@code distinct()} in parallel pipelines is
 371      * relatively expensive (requires that the operation act as a full barrier,
 372      * with substantial buffering overhead), and stability is often not needed.
 373      * Using an unordered stream source (such as {@link #generate(Supplier)})
 374      * or removing the ordering constraint with {@link #unordered()} may result
 375      * in significantly more efficient execution for {@code distinct()} in parallel
 376      * pipelines, if the semantics of your situation permit.  If consistency
 377      * with encounter order is required, and you are experiencing poor performance
 378      * or memory utilization with {@code distinct()} in parallel pipelines,
 379      * switching to sequential execution with {@link #sequential()} may improve
 380      * performance.
 381      *
 382      * @return the new stream
 383      */
 384     Stream<T> distinct();
 385 
 386     /**
 387      * Returns a stream consisting of the elements of this stream, sorted
 388      * according to natural order.  If the elements of this stream are not
 389      * {@code Comparable}, a {@code java.lang.ClassCastException} may be thrown
 390      * when the terminal operation is executed.
 391      *
 392      * <p>For ordered streams, the sort is stable.  For unordered streams, no
 393      * stability guarantees are made.
 394      *
 395      * <p>This is a <a href="package-summary.html#StreamOps">stateful
 396      * intermediate operation</a>.
 397      *
 398      * @return the new stream
 399      */
 400     Stream<T> sorted();
 401 
 402     /**
 403      * Returns a stream consisting of the elements of this stream, sorted
 404      * according to the provided {@code Comparator}.
 405      *
 406      * <p>For ordered streams, the sort is stable.  For unordered streams, no
 407      * stability guarantees are made.
 408      *
 409      * <p>This is a <a href="package-summary.html#StreamOps">stateful
 410      * intermediate operation</a>.
 411      *
 412      * @param comparator a <a href="package-summary.html#NonInterference">non-interfering</a>,
 413      *                   <a href="package-summary.html#Statelessness">stateless</a>
 414      *                   {@code Comparator} to be used to compare stream elements
 415      * @return the new stream
 416      */
 417     Stream<T> sorted(Comparator<? super T> comparator);
 418 
 419     /**
 420      * Returns a stream consisting of the elements of this stream, additionally
 421      * performing the provided action on each element as elements are consumed
 422      * from the resulting stream.
 423      *
 424      * <p>This is an <a href="package-summary.html#StreamOps">intermediate
 425      * operation</a>.
 426      *
 427      * <p>For parallel stream pipelines, the action may be called at
 428      * whatever time and in whatever thread the element is made available by the
 429      * upstream operation.  If the action modifies shared state,
 430      * it is responsible for providing the required synchronization.
 431      *
 432      * @apiNote This method exists mainly to support debugging, where you want
 433      * to see the elements as they flow past a certain point in a pipeline:
 434      * <pre>{@code
 435      *     Stream.of("one", "two", "three", "four")
 436      *         .filter(e -> e.length() > 3)
 437      *         .peek(e -> System.out.println("Filtered value: " + e))
 438      *         .map(String::toUpperCase)
 439      *         .peek(e -> System.out.println("Mapped value: " + e))
 440      *         .collect(Collectors.toList());
 441      * }</pre>
 442      *
 443      * <p>In cases where the stream implementation is able to optimize away the
 444      * production of some or all the elements (such as with short-circuiting
 445      * operations like {@code findFirst}, or in the example described in
 446      * {@link #count}), the action will not be invoked for those elements.
 447      *
 448      * @param action a <a href="package-summary.html#NonInterference">
 449      *                 non-interfering</a> action to perform on the elements as
 450      *                 they are consumed from the stream
 451      * @return the new stream
 452      */
 453     Stream<T> peek(Consumer<? super T> action);
 454 
 455     /**
 456      * Returns a stream consisting of the elements of this stream, truncated
 457      * to be no longer than {@code maxSize} in length.
 458      *
 459      * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting
 460      * stateful intermediate operation</a>.
 461      *
 462      * @apiNote
 463      * While {@code limit()} is generally a cheap operation on sequential
 464      * stream pipelines, it can be quite expensive on ordered parallel pipelines,
 465      * especially for large values of {@code maxSize}, since {@code limit(n)}
 466      * is constrained to return not just any <em>n</em> elements, but the
 467      * <em>first n</em> elements in the encounter order.  Using an unordered
 468      * stream source (such as {@link #generate(Supplier)}) or removing the
 469      * ordering constraint with {@link #unordered()} may result in significant
 470      * speedups of {@code limit()} in parallel pipelines, if the semantics of
 471      * your situation permit.  If consistency with encounter order is required,
 472      * and you are experiencing poor performance or memory utilization with
 473      * {@code limit()} in parallel pipelines, switching to sequential execution
 474      * with {@link #sequential()} may improve performance.
 475      *
 476      * @param maxSize the number of elements the stream should be limited to
 477      * @return the new stream
 478      * @throws IllegalArgumentException if {@code maxSize} is negative
 479      */
 480     Stream<T> limit(long maxSize);
 481 
 482     /**
 483      * Returns a stream consisting of the remaining elements of this stream
 484      * after discarding the first {@code n} elements of the stream.
 485      * If this stream contains fewer than {@code n} elements then an
 486      * empty stream will be returned.
 487      *
 488      * <p>This is a <a href="package-summary.html#StreamOps">stateful
 489      * intermediate operation</a>.
 490      *
 491      * @apiNote
 492      * While {@code skip()} is generally a cheap operation on sequential
 493      * stream pipelines, it can be quite expensive on ordered parallel pipelines,
 494      * especially for large values of {@code n}, since {@code skip(n)}
 495      * is constrained to skip not just any <em>n</em> elements, but the
 496      * <em>first n</em> elements in the encounter order.  Using an unordered
 497      * stream source (such as {@link #generate(Supplier)}) or removing the
 498      * ordering constraint with {@link #unordered()} may result in significant
 499      * speedups of {@code skip()} in parallel pipelines, if the semantics of
 500      * your situation permit.  If consistency with encounter order is required,
 501      * and you are experiencing poor performance or memory utilization with
 502      * {@code skip()} in parallel pipelines, switching to sequential execution
 503      * with {@link #sequential()} may improve performance.
 504      *
 505      * @param n the number of leading elements to skip
 506      * @return the new stream
 507      * @throws IllegalArgumentException if {@code n} is negative
 508      */
 509     Stream<T> skip(long n);
 510 
 511     /**
 512      * Returns, if this stream is ordered, a stream consisting of the longest
 513      * prefix of elements taken from this stream that match the given predicate.
 514      * Otherwise returns, if this stream is unordered, a stream consisting of a
 515      * subset of elements taken from this stream that match the given predicate.
 516      *
 517      * <p>If this stream is ordered then the longest prefix is a contiguous
 518      * sequence of elements of this stream that match the given predicate.  The
 519      * first element of the sequence is the first element of this stream, and
 520      * the element immediately following the last element of the sequence does
 521      * not match the given predicate.
 522      *
 523      * <p>If this stream is unordered, and some (but not all) elements of this
 524      * stream match the given predicate, then the behavior of this operation is
 525      * nondeterministic; it is free to take any subset of matching elements
 526      * (which includes the empty set).
 527      *
 528      * <p>Independent of whether this stream is ordered or unordered if all
 529      * elements of this stream match the given predicate then this operation
 530      * takes all elements (the result is the same as the input), or if no
 531      * elements of the stream match the given predicate then no elements are
 532      * taken (the result is an empty stream).
 533      *
 534      * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting
 535      * stateful intermediate operation</a>.
 536      *
 537      * @implSpec
 538      * The default implementation obtains the {@link #spliterator() spliterator}
 539      * of this stream, wraps that spliterator so as to support the semantics
 540      * of this operation on traversal, and returns a new stream associated with
 541      * the wrapped spliterator.  The returned stream preserves the execution
 542      * characteristics of this stream (namely parallel or sequential execution
 543      * as per {@link #isParallel()}) but the wrapped spliterator may choose to
 544      * not support splitting.  When the returned stream is closed, the close
 545      * handlers for both the returned and this stream are invoked.
 546      *
 547      * @apiNote
 548      * While {@code takeWhile()} is generally a cheap operation on sequential
 549      * stream pipelines, it can be quite expensive on ordered parallel
 550      * pipelines, since the operation is constrained to return not just any
 551      * valid prefix, but the longest prefix of elements in the encounter order.
 552      * Using an unordered stream source (such as {@link #generate(Supplier)}) or
 553      * removing the ordering constraint with {@link #unordered()} may result in
 554      * significant speedups of {@code takeWhile()} in parallel pipelines, if the
 555      * semantics of your situation permit.  If consistency with encounter order
 556      * is required, and you are experiencing poor performance or memory
 557      * utilization with {@code takeWhile()} in parallel pipelines, switching to
 558      * sequential execution with {@link #sequential()} may improve performance.
 559      *
 560      * @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>,
 561      *                  <a href="package-summary.html#Statelessness">stateless</a>
 562      *                  predicate to apply to elements to determine the longest
 563      *                  prefix of elements.
 564      * @return the new stream
 565      * @since 9
 566      */
 567     default Stream<T> takeWhile(Predicate<? super T> predicate) {
 568         Objects.requireNonNull(predicate);
 569         // Reuses the unordered spliterator, which, when encounter is present,
 570         // is safe to use as long as it configured not to split
 571         return StreamSupport.stream(
 572                 new WhileOps.UnorderedWhileSpliterator.OfRef.Taking<>(spliterator(), true, predicate),
 573                 isParallel()).onClose(this::close);
 574     }
 575 
 576     /**
 577      * Returns, if this stream is ordered, a stream consisting of the remaining
 578      * elements of this stream after dropping the longest prefix of elements
 579      * that match the given predicate.  Otherwise returns, if this stream is
 580      * unordered, a stream consisting of the remaining elements of this stream
 581      * after dropping a subset of elements that match the given predicate.
 582      *
 583      * <p>If this stream is ordered then the longest prefix is a contiguous
 584      * sequence of elements of this stream that match the given predicate.  The
 585      * first element of the sequence is the first element of this stream, and
 586      * the element immediately following the last element of the sequence does
 587      * not match the given predicate.
 588      *
 589      * <p>If this stream is unordered, and some (but not all) elements of this
 590      * stream match the given predicate, then the behavior of this operation is
 591      * nondeterministic; it is free to drop any subset of matching elements
 592      * (which includes the empty set).
 593      *
 594      * <p>Independent of whether this stream is ordered or unordered if all
 595      * elements of this stream match the given predicate then this operation
 596      * drops all elements (the result is an empty stream), or if no elements of
 597      * the stream match the given predicate then no elements are dropped (the
 598      * result is the same as the input).
 599      *
 600      * <p>This is a <a href="package-summary.html#StreamOps">stateful
 601      * intermediate operation</a>.
 602      *
 603      * @implSpec
 604      * The default implementation obtains the {@link #spliterator() spliterator}
 605      * of this stream, wraps that spliterator so as to support the semantics
 606      * of this operation on traversal, and returns a new stream associated with
 607      * the wrapped spliterator.  The returned stream preserves the execution
 608      * characteristics of this stream (namely parallel or sequential execution
 609      * as per {@link #isParallel()}) but the wrapped spliterator may choose to
 610      * not support splitting.  When the returned stream is closed, the close
 611      * handlers for both the returned and this stream are invoked.
 612      *
 613      * @apiNote
 614      * While {@code dropWhile()} is generally a cheap operation on sequential
 615      * stream pipelines, it can be quite expensive on ordered parallel
 616      * pipelines, since the operation is constrained to return not just any
 617      * valid prefix, but the longest prefix of elements in the encounter order.
 618      * Using an unordered stream source (such as {@link #generate(Supplier)}) or
 619      * removing the ordering constraint with {@link #unordered()} may result in
 620      * significant speedups of {@code dropWhile()} in parallel pipelines, if the
 621      * semantics of your situation permit.  If consistency with encounter order
 622      * is required, and you are experiencing poor performance or memory
 623      * utilization with {@code dropWhile()} in parallel pipelines, switching to
 624      * sequential execution with {@link #sequential()} may improve performance.
 625      *
 626      * @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>,
 627      *                  <a href="package-summary.html#Statelessness">stateless</a>
 628      *                  predicate to apply to elements to determine the longest
 629      *                  prefix of elements.
 630      * @return the new stream
 631      * @since 9
 632      */
 633     default Stream<T> dropWhile(Predicate<? super T> predicate) {
 634         Objects.requireNonNull(predicate);
 635         // Reuses the unordered spliterator, which, when encounter is present,
 636         // is safe to use as long as it configured not to split
 637         return StreamSupport.stream(
 638                 new WhileOps.UnorderedWhileSpliterator.OfRef.Dropping<>(spliterator(), true, predicate),
 639                 isParallel()).onClose(this::close);
 640     }
 641 
 642     /**
 643      * Performs an action for each element of this stream.
 644      *
 645      * <p>This is a <a href="package-summary.html#StreamOps">terminal
 646      * operation</a>.
 647      *
 648      * <p>The behavior of this operation is explicitly nondeterministic.
 649      * For parallel stream pipelines, this operation does <em>not</em>
 650      * guarantee to respect the encounter order of the stream, as doing so
 651      * would sacrifice the benefit of parallelism.  For any given element, the
 652      * action may be performed at whatever time and in whatever thread the
 653      * library chooses.  If the action accesses shared state, it is
 654      * responsible for providing the required synchronization.
 655      *
 656      * @param action a <a href="package-summary.html#NonInterference">
 657      *               non-interfering</a> action to perform on the elements
 658      */
 659     void forEach(Consumer<? super T> action);
 660 
 661     /**
 662      * Performs an action for each element of this stream, in the encounter
 663      * order of the stream if the stream has a defined encounter order.
 664      *
 665      * <p>This is a <a href="package-summary.html#StreamOps">terminal
 666      * operation</a>.
 667      *
 668      * <p>This operation processes the elements one at a time, in encounter
 669      * order if one exists.  Performing the action for one element
 670      * <a href="../concurrent/package-summary.html#MemoryVisibility"><i>happens-before</i></a>
 671      * performing the action for subsequent elements, but for any given element,
 672      * the action may be performed in whatever thread the library chooses.
 673      *
 674      * @param action a <a href="package-summary.html#NonInterference">
 675      *               non-interfering</a> action to perform on the elements
 676      * @see #forEach(Consumer)
 677      */
 678     void forEachOrdered(Consumer<? super T> action);
 679 
 680     /**
 681      * Returns an array containing the elements of this stream.
 682      *
 683      * <p>This is a <a href="package-summary.html#StreamOps">terminal
 684      * operation</a>.
 685      *
 686      * @return an array, whose {@linkplain Class#getComponentType runtime component
 687      * type} is {@code Object}, containing the elements of this stream
 688      */
 689     Object[] toArray();
 690 
 691     /**
 692      * Returns an array containing the elements of this stream, using the
 693      * provided {@code generator} function to allocate the returned array, as
 694      * well as any additional arrays that might be required for a partitioned
 695      * execution or for resizing.
 696      *
 697      * <p>This is a <a href="package-summary.html#StreamOps">terminal
 698      * operation</a>.
 699      *
 700      * @apiNote
 701      * The generator function takes an integer, which is the size of the
 702      * desired array, and produces an array of the desired size.  This can be
 703      * concisely expressed with an array constructor reference:
 704      * <pre>{@code
 705      *     Person[] men = people.stream()
 706      *                          .filter(p -> p.getGender() == MALE)
 707      *                          .toArray(Person[]::new);
 708      * }</pre>
 709      *
 710      * @param <A> the component type of the resulting array
 711      * @param generator a function which produces a new array of the desired
 712      *                  type and the provided length
 713      * @return an array containing the elements in this stream
 714      * @throws ArrayStoreException if the runtime type of any element of this
 715      *         stream is not assignable to the {@linkplain Class#getComponentType
 716      *         runtime component type} of the generated array
 717      */
 718     <A> A[] toArray(IntFunction<A[]> generator);
 719 
 720     /**
 721      * Performs a <a href="package-summary.html#Reduction">reduction</a> on the
 722      * elements of this stream, using the provided identity value and an
 723      * <a href="package-summary.html#Associativity">associative</a>
 724      * accumulation function, and returns the reduced value.  This is equivalent
 725      * to:
 726      * <pre>{@code
 727      *     T result = identity;
 728      *     for (T element : this stream)
 729      *         result = accumulator.apply(result, element)
 730      *     return result;
 731      * }</pre>
 732      *
 733      * but is not constrained to execute sequentially.
 734      *
 735      * <p>The {@code identity} value must be an identity for the accumulator
 736      * function. This means that for all {@code t},
 737      * {@code accumulator.apply(identity, t)} is equal to {@code t}.
 738      * The {@code accumulator} function must be an
 739      * <a href="package-summary.html#Associativity">associative</a> function.
 740      *
 741      * <p>This is a <a href="package-summary.html#StreamOps">terminal
 742      * operation</a>.
 743      *
 744      * @apiNote Sum, min, max, average, and string concatenation are all special
 745      * cases of reduction. Summing a stream of numbers can be expressed as:
 746      *
 747      * <pre>{@code
 748      *     Integer sum = integers.reduce(0, (a, b) -> a+b);
 749      * }</pre>
 750      *
 751      * or:
 752      *
 753      * <pre>{@code
 754      *     Integer sum = integers.reduce(0, Integer::sum);
 755      * }</pre>
 756      *
 757      * <p>While this may seem a more roundabout way to perform an aggregation
 758      * compared to simply mutating a running total in a loop, reduction
 759      * operations parallelize more gracefully, without needing additional
 760      * synchronization and with greatly reduced risk of data races.
 761      *
 762      * @param identity the identity value for the accumulating function
 763      * @param accumulator an <a href="package-summary.html#Associativity">associative</a>,
 764      *                    <a href="package-summary.html#NonInterference">non-interfering</a>,
 765      *                    <a href="package-summary.html#Statelessness">stateless</a>
 766      *                    function for combining two values
 767      * @return the result of the reduction
 768      */
 769     T reduce(T identity, BinaryOperator<T> accumulator);
 770 
 771     /**
 772      * Performs a <a href="package-summary.html#Reduction">reduction</a> on the
 773      * elements of this stream, using an
 774      * <a href="package-summary.html#Associativity">associative</a> accumulation
 775      * function, and returns an {@code Optional} describing the reduced value,
 776      * if any. This is equivalent to:
 777      * <pre>{@code
 778      *     boolean foundAny = false;
 779      *     T result = null;
 780      *     for (T element : this stream) {
 781      *         if (!foundAny) {
 782      *             foundAny = true;
 783      *             result = element;
 784      *         }
 785      *         else
 786      *             result = accumulator.apply(result, element);
 787      *     }
 788      *     return foundAny ? Optional.of(result) : Optional.empty();
 789      * }</pre>
 790      *
 791      * but is not constrained to execute sequentially.
 792      *
 793      * <p>The {@code accumulator} function must be an
 794      * <a href="package-summary.html#Associativity">associative</a> function.
 795      *
 796      * <p>This is a <a href="package-summary.html#StreamOps">terminal
 797      * operation</a>.
 798      *
 799      * @param accumulator an <a href="package-summary.html#Associativity">associative</a>,
 800      *                    <a href="package-summary.html#NonInterference">non-interfering</a>,
 801      *                    <a href="package-summary.html#Statelessness">stateless</a>
 802      *                    function for combining two values
 803      * @return an {@link Optional} describing the result of the reduction
 804      * @throws NullPointerException if the result of the reduction is null
 805      * @see #reduce(Object, BinaryOperator)
 806      * @see #min(Comparator)
 807      * @see #max(Comparator)
 808      */
 809     Optional<T> reduce(BinaryOperator<T> accumulator);
 810 
 811     /**
 812      * Performs a <a href="package-summary.html#Reduction">reduction</a> on the
 813      * elements of this stream, using the provided identity, accumulation and
 814      * combining functions.  This is equivalent to:
 815      * <pre>{@code
 816      *     U result = identity;
 817      *     for (T element : this stream)
 818      *         result = accumulator.apply(result, element)
 819      *     return result;
 820      * }</pre>
 821      *
 822      * but is not constrained to execute sequentially.
 823      *
 824      * <p>The {@code identity} value must be an identity for the combiner
 825      * function.  This means that for all {@code u}, {@code combiner(identity, u)}
 826      * is equal to {@code u}.  Additionally, the {@code combiner} function
 827      * must be compatible with the {@code accumulator} function; for all
 828      * {@code u} and {@code t}, the following must hold:
 829      * <pre>{@code
 830      *     combiner.apply(u, accumulator.apply(identity, t)) == accumulator.apply(u, t)
 831      * }</pre>
 832      *
 833      * <p>This is a <a href="package-summary.html#StreamOps">terminal
 834      * operation</a>.
 835      *
 836      * @apiNote Many reductions using this form can be represented more simply
 837      * by an explicit combination of {@code map} and {@code reduce} operations.
 838      * The {@code accumulator} function acts as a fused mapper and accumulator,
 839      * which can sometimes be more efficient than separate mapping and reduction,
 840      * such as when knowing the previously reduced value allows you to avoid
 841      * some computation.
 842      *
 843      * @param <U> The type of the result
 844      * @param identity the identity value for the combiner function
 845      * @param accumulator an <a href="package-summary.html#Associativity">associative</a>,
 846      *                    <a href="package-summary.html#NonInterference">non-interfering</a>,
 847      *                    <a href="package-summary.html#Statelessness">stateless</a>
 848      *                    function for incorporating an additional element into a result
 849      * @param combiner an <a href="package-summary.html#Associativity">associative</a>,
 850      *                    <a href="package-summary.html#NonInterference">non-interfering</a>,
 851      *                    <a href="package-summary.html#Statelessness">stateless</a>
 852      *                    function for combining two values, which must be
 853      *                    compatible with the accumulator function
 854      * @return the result of the reduction
 855      * @see #reduce(BinaryOperator)
 856      * @see #reduce(Object, BinaryOperator)
 857      */
 858     <U> U reduce(U identity,
 859                  BiFunction<U, ? super T, U> accumulator,
 860                  BinaryOperator<U> combiner);
 861 
 862     /**
 863      * Performs a <a href="package-summary.html#MutableReduction">mutable
 864      * reduction</a> operation on the elements of this stream.  A mutable
 865      * reduction is one in which the reduced value is a mutable result container,
 866      * such as an {@code ArrayList}, and elements are incorporated by updating
 867      * the state of the result rather than by replacing the result.  This
 868      * produces a result equivalent to:
 869      * <pre>{@code
 870      *     R result = supplier.get();
 871      *     for (T element : this stream)
 872      *         accumulator.accept(result, element);
 873      *     return result;
 874      * }</pre>
 875      *
 876      * <p>Like {@link #reduce(Object, BinaryOperator)}, {@code collect} operations
 877      * can be parallelized without requiring additional synchronization.
 878      *
 879      * <p>This is a <a href="package-summary.html#StreamOps">terminal
 880      * operation</a>.
 881      *
 882      * @apiNote There are many existing classes in the JDK whose signatures are
 883      * well-suited for use with method references as arguments to {@code collect()}.
 884      * For example, the following will accumulate strings into an {@code ArrayList}:
 885      * <pre>{@code
 886      *     List<String> asList = stringStream.collect(ArrayList::new, ArrayList::add,
 887      *                                                ArrayList::addAll);
 888      * }</pre>
 889      *
 890      * <p>The following will take a stream of strings and concatenates them into a
 891      * single string:
 892      * <pre>{@code
 893      *     String concat = stringStream.collect(StringBuilder::new, StringBuilder::append,
 894      *                                          StringBuilder::append)
 895      *                                 .toString();
 896      * }</pre>
 897      *
 898      * @param <R> the type of the mutable result container
 899      * @param supplier a function that creates a new mutable result container.
 900      *                 For a parallel execution, this function may be called
 901      *                 multiple times and must return a fresh value each time.
 902      * @param accumulator an <a href="package-summary.html#Associativity">associative</a>,
 903      *                    <a href="package-summary.html#NonInterference">non-interfering</a>,
 904      *                    <a href="package-summary.html#Statelessness">stateless</a>
 905      *                    function that must fold an element into a result
 906      *                    container.
 907      * @param combiner an <a href="package-summary.html#Associativity">associative</a>,
 908      *                    <a href="package-summary.html#NonInterference">non-interfering</a>,
 909      *                    <a href="package-summary.html#Statelessness">stateless</a>
 910      *                    function that accepts two partial result containers
 911      *                    and merges them, which must be compatible with the
 912      *                    accumulator function.  The combiner function must fold
 913      *                    the elements from the second result container into the
 914      *                    first result container.
 915      * @return the result of the reduction
 916      */
 917     <R> R collect(Supplier<R> supplier,
 918                   BiConsumer<R, ? super T> accumulator,
 919                   BiConsumer<R, R> combiner);
 920 
 921     /**
 922      * Performs a <a href="package-summary.html#MutableReduction">mutable
 923      * reduction</a> operation on the elements of this stream using a
 924      * {@code Collector}.  A {@code Collector}
 925      * encapsulates the functions used as arguments to
 926      * {@link #collect(Supplier, BiConsumer, BiConsumer)}, allowing for reuse of
 927      * collection strategies and composition of collect operations such as
 928      * multiple-level grouping or partitioning.
 929      *
 930      * <p>If the stream is parallel, and the {@code Collector}
 931      * is {@link Collector.Characteristics#CONCURRENT concurrent}, and
 932      * either the stream is unordered or the collector is
 933      * {@link Collector.Characteristics#UNORDERED unordered},
 934      * then a concurrent reduction will be performed (see {@link Collector} for
 935      * details on concurrent reduction.)
 936      *
 937      * <p>This is a <a href="package-summary.html#StreamOps">terminal
 938      * operation</a>.
 939      *
 940      * <p>When executed in parallel, multiple intermediate results may be
 941      * instantiated, populated, and merged so as to maintain isolation of
 942      * mutable data structures.  Therefore, even when executed in parallel
 943      * with non-thread-safe data structures (such as {@code ArrayList}), no
 944      * additional synchronization is needed for a parallel reduction.
 945      *
 946      * @apiNote
 947      * The following will accumulate strings into an ArrayList:
 948      * <pre>{@code
 949      *     List<String> asList = stringStream.collect(Collectors.toList());
 950      * }</pre>
 951      *
 952      * <p>The following will classify {@code Person} objects by city:
 953      * <pre>{@code
 954      *     Map<String, List<Person>> peopleByCity
 955      *         = personStream.collect(Collectors.groupingBy(Person::getCity));
 956      * }</pre>
 957      *
 958      * <p>The following will classify {@code Person} objects by state and city,
 959      * cascading two {@code Collector}s together:
 960      * <pre>{@code
 961      *     Map<String, Map<String, List<Person>>> peopleByStateAndCity
 962      *         = personStream.collect(Collectors.groupingBy(Person::getState,
 963      *                                                      Collectors.groupingBy(Person::getCity)));
 964      * }</pre>
 965      *
 966      * @param <R> the type of the result
 967      * @param <A> the intermediate accumulation type of the {@code Collector}
 968      * @param collector the {@code Collector} describing the reduction
 969      * @return the result of the reduction
 970      * @see #collect(Supplier, BiConsumer, BiConsumer)
 971      * @see Collectors
 972      */
 973     <R, A> R collect(Collector<? super T, A, R> collector);
 974 
 975     /**
 976      * Returns the minimum element of this stream according to the provided
 977      * {@code Comparator}.  This is a special case of a
 978      * <a href="package-summary.html#Reduction">reduction</a>.
 979      *
 980      * <p>This is a <a href="package-summary.html#StreamOps">terminal operation</a>.
 981      *
 982      * @param comparator a <a href="package-summary.html#NonInterference">non-interfering</a>,
 983      *                   <a href="package-summary.html#Statelessness">stateless</a>
 984      *                   {@code Comparator} to compare elements of this stream
 985      * @return an {@code Optional} describing the minimum element of this stream,
 986      * or an empty {@code Optional} if the stream is empty
 987      * @throws NullPointerException if the minimum element is null
 988      */
 989     Optional<T> min(Comparator<? super T> comparator);
 990 
 991     /**
 992      * Returns the maximum element of this stream according to the provided
 993      * {@code Comparator}.  This is a special case of a
 994      * <a href="package-summary.html#Reduction">reduction</a>.
 995      *
 996      * <p>This is a <a href="package-summary.html#StreamOps">terminal
 997      * operation</a>.
 998      *
 999      * @param comparator a <a href="package-summary.html#NonInterference">non-interfering</a>,
1000      *                   <a href="package-summary.html#Statelessness">stateless</a>
1001      *                   {@code Comparator} to compare elements of this stream
1002      * @return an {@code Optional} describing the maximum element of this stream,
1003      * or an empty {@code Optional} if the stream is empty
1004      * @throws NullPointerException if the maximum element is null
1005      */
1006     Optional<T> max(Comparator<? super T> comparator);
1007 
1008     /**
1009      * Returns the count of elements in this stream.  This is a special case of
1010      * a <a href="package-summary.html#Reduction">reduction</a> and is
1011      * equivalent to:
1012      * <pre>{@code
1013      *     return mapToLong(e -> 1L).sum();
1014      * }</pre>
1015      *
1016      * <p>This is a <a href="package-summary.html#StreamOps">terminal operation</a>.
1017      *
1018      * @apiNote
1019      * An implementation may choose to not execute the stream pipeline (either
1020      * sequentially or in parallel) if it is capable of computing the count
1021      * directly from the stream source.  In such cases no source elements will
1022      * be traversed and no intermediate operations will be evaluated.
1023      * Behavioral parameters with side-effects, which are strongly discouraged
1024      * except for harmless cases such as debugging, may be affected.  For
1025      * example, consider the following stream:
1026      * <pre>{@code
1027      *     List<String> l = Arrays.asList("A", "B", "C", "D");
1028      *     long count = l.stream().peek(System.out::println).count();
1029      * }</pre>
1030      * The number of elements covered by the stream source, a {@code List}, is
1031      * known and the intermediate operation, {@code peek}, does not inject into
1032      * or remove elements from the stream (as may be the case for
1033      * {@code flatMap} or {@code filter} operations).  Thus the count is the
1034      * size of the {@code List} and there is no need to execute the pipeline
1035      * and, as a side-effect, print out the list elements.
1036      *
1037      * @return the count of elements in this stream
1038      */
1039     long count();
1040 
1041     /**
1042      * Returns whether any elements of this stream match the provided
1043      * predicate.  May not evaluate the predicate on all elements if not
1044      * necessary for determining the result.  If the stream is empty then
1045      * {@code false} is returned and the predicate is not evaluated.
1046      *
1047      * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting
1048      * terminal operation</a>.
1049      *
1050      * @apiNote
1051      * This method evaluates the <em>existential quantification</em> of the
1052      * predicate over the elements of the stream (for some x P(x)).
1053      *
1054      * @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>,
1055      *                  <a href="package-summary.html#Statelessness">stateless</a>
1056      *                  predicate to apply to elements of this stream
1057      * @return {@code true} if any elements of the stream match the provided
1058      * predicate, otherwise {@code false}
1059      */
1060     boolean anyMatch(Predicate<? super T> predicate);
1061 
1062     /**
1063      * Returns whether all elements of this stream match the provided predicate.
1064      * May not evaluate the predicate on all elements if not necessary for
1065      * determining the result.  If the stream is empty then {@code true} is
1066      * returned and the predicate is not evaluated.
1067      *
1068      * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting
1069      * terminal operation</a>.
1070      *
1071      * @apiNote
1072      * This method evaluates the <em>universal quantification</em> of the
1073      * predicate over the elements of the stream (for all x P(x)).  If the
1074      * stream is empty, the quantification is said to be <em>vacuously
1075      * satisfied</em> and is always {@code true} (regardless of P(x)).
1076      *
1077      * @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>,
1078      *                  <a href="package-summary.html#Statelessness">stateless</a>
1079      *                  predicate to apply to elements of this stream
1080      * @return {@code true} if either all elements of the stream match the
1081      * provided predicate or the stream is empty, otherwise {@code false}
1082      */
1083     boolean allMatch(Predicate<? super T> predicate);
1084 
1085     /**
1086      * Returns whether no elements of this stream match the provided predicate.
1087      * May not evaluate the predicate on all elements if not necessary for
1088      * determining the result.  If the stream is empty then {@code true} is
1089      * returned and the predicate is not evaluated.
1090      *
1091      * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting
1092      * terminal operation</a>.
1093      *
1094      * @apiNote
1095      * This method evaluates the <em>universal quantification</em> of the
1096      * negated predicate over the elements of the stream (for all x ~P(x)).  If
1097      * the stream is empty, the quantification is said to be vacuously satisfied
1098      * and is always {@code true}, regardless of P(x).
1099      *
1100      * @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>,
1101      *                  <a href="package-summary.html#Statelessness">stateless</a>
1102      *                  predicate to apply to elements of this stream
1103      * @return {@code true} if either no elements of the stream match the
1104      * provided predicate or the stream is empty, otherwise {@code false}
1105      */
1106     boolean noneMatch(Predicate<? super T> predicate);
1107 
1108     /**
1109      * Returns an {@link Optional} describing the first element of this stream,
1110      * or an empty {@code Optional} if the stream is empty.  If the stream has
1111      * no encounter order, then any element may be returned.
1112      *
1113      * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting
1114      * terminal operation</a>.
1115      *
1116      * @return an {@code Optional} describing the first element of this stream,
1117      * or an empty {@code Optional} if the stream is empty
1118      * @throws NullPointerException if the element selected is null
1119      */
1120     Optional<T> findFirst();
1121 
1122     /**
1123      * Returns an {@link Optional} describing some element of the stream, or an
1124      * empty {@code Optional} if the stream is empty.
1125      *
1126      * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting
1127      * terminal operation</a>.
1128      *
1129      * <p>The behavior of this operation is explicitly nondeterministic; it is
1130      * free to select any element in the stream.  This is to allow for maximal
1131      * performance in parallel operations; the cost is that multiple invocations
1132      * on the same source may not return the same result.  (If a stable result
1133      * is desired, use {@link #findFirst()} instead.)
1134      *
1135      * @return an {@code Optional} describing some element of this stream, or an
1136      * empty {@code Optional} if the stream is empty
1137      * @throws NullPointerException if the element selected is null
1138      * @see #findFirst()
1139      */
1140     Optional<T> findAny();
1141 
1142     // Static factories
1143 
1144     /**
1145      * Returns a builder for a {@code Stream}.
1146      *
1147      * @param <T> type of elements
1148      * @return a stream builder
1149      */
1150     public static<T> Builder<T> builder() {
1151         return new Streams.StreamBuilderImpl<>();
1152     }
1153 
1154     /**
1155      * Returns an empty sequential {@code Stream}.
1156      *
1157      * @param <T> the type of stream elements
1158      * @return an empty sequential stream
1159      */
1160     public static<T> Stream<T> empty() {
1161         return StreamSupport.stream(Spliterators.<T>emptySpliterator(), false);
1162     }
1163 
1164     /**
1165      * Returns a sequential {@code Stream} containing a single element.
1166      *
1167      * @param t the single element
1168      * @param <T> the type of stream elements
1169      * @return a singleton sequential stream
1170      */
1171     public static<T> Stream<T> of(T t) {
1172         return StreamSupport.stream(new Streams.StreamBuilderImpl<>(t), false);
1173     }
1174 
1175     /**
1176      * Returns a sequential {@code Stream} containing a single element, if
1177      * non-null, otherwise returns an empty {@code Stream}.
1178      *
1179      * @param t the single element
1180      * @param <T> the type of stream elements
1181      * @return a stream with a single element if the specified element
1182      *         is non-null, otherwise an empty stream
1183      * @since 9
1184      */
1185     public static<T> Stream<T> ofNullable(T t) {
1186         return t == null ? Stream.empty()
1187                          : StreamSupport.stream(new Streams.StreamBuilderImpl<>(t), false);
1188     }
1189 
1190     /**
1191      * Returns a sequential ordered stream whose elements are the specified values.
1192      *
1193      * @param <T> the type of stream elements
1194      * @param values the elements of the new stream
1195      * @return the new stream
1196      */
1197     @SafeVarargs
1198     @SuppressWarnings("varargs") // Creating a stream from an array is safe
1199     public static<T> Stream<T> of(T... values) {
1200         return Arrays.stream(values);
1201     }
1202 
1203     /**
1204      * Returns an infinite sequential ordered {@code Stream} produced by iterative
1205      * application of a function {@code f} to an initial element {@code seed},
1206      * producing a {@code Stream} consisting of {@code seed}, {@code f(seed)},
1207      * {@code f(f(seed))}, etc.
1208      *
1209      * <p>The first element (position {@code 0}) in the {@code Stream} will be
1210      * the provided {@code seed}.  For {@code n > 0}, the element at position
1211      * {@code n}, will be the result of applying the function {@code f} to the
1212      * element at position {@code n - 1}.
1213      *
1214      * <p>The action of applying {@code f} for one element
1215      * <a href="../concurrent/package-summary.html#MemoryVisibility"><i>happens-before</i></a>
1216      * the action of applying {@code f} for subsequent elements.  For any given
1217      * element the action may be performed in whatever thread the library
1218      * chooses.
1219      *
1220      * @param <T> the type of stream elements
1221      * @param seed the initial element
1222      * @param f a function to be applied to the previous element to produce
1223      *          a new element
1224      * @return a new sequential {@code Stream}
1225      */
1226     public static<T> Stream<T> iterate(final T seed, final UnaryOperator<T> f) {
1227         Objects.requireNonNull(f);
1228         Spliterator<T> spliterator = new Spliterators.AbstractSpliterator<>(Long.MAX_VALUE,
1229                Spliterator.ORDERED | Spliterator.IMMUTABLE) {
1230             T prev;
1231             boolean started;
1232 
1233             @Override
1234             public boolean tryAdvance(Consumer<? super T> action) {
1235                 Objects.requireNonNull(action);
1236                 T t;
1237                 if (started)
1238                     t = f.apply(prev);
1239                 else {
1240                     t = seed;
1241                     started = true;
1242                 }
1243                 action.accept(prev = t);
1244                 return true;
1245             }
1246         };
1247         return StreamSupport.stream(spliterator, false);
1248     }
1249 
1250     /**
1251      * Returns a sequential ordered {@code Stream} produced by iterative
1252      * application of the given {@code next} function to an initial element,
1253      * conditioned on satisfying the given {@code hasNext} predicate.  The
1254      * stream terminates as soon as the {@code hasNext} predicate returns false.
1255      *
1256      * <p>{@code Stream.iterate} should produce the same sequence of elements as
1257      * produced by the corresponding for-loop:
1258      * <pre>{@code
1259      *     for (T index=seed; hasNext.test(index); index = next.apply(index)) {
1260      *         ...
1261      *     }
1262      * }</pre>
1263      *
1264      * <p>The resulting sequence may be empty if the {@code hasNext} predicate
1265      * does not hold on the seed value.  Otherwise the first element will be the
1266      * supplied {@code seed} value, the next element (if present) will be the
1267      * result of applying the {@code next} function to the {@code seed} value,
1268      * and so on iteratively until the {@code hasNext} predicate indicates that
1269      * the stream should terminate.
1270      *
1271      * <p>The action of applying the {@code hasNext} predicate to an element
1272      * <a href="../concurrent/package-summary.html#MemoryVisibility"><i>happens-before</i></a>
1273      * the action of applying the {@code next} function to that element.  The
1274      * action of applying the {@code next} function for one element
1275      * <i>happens-before</i> the action of applying the {@code hasNext}
1276      * predicate for subsequent elements.  For any given element an action may
1277      * be performed in whatever thread the library chooses.
1278      *
1279      * @param <T> the type of stream elements
1280      * @param seed the initial element
1281      * @param hasNext a predicate to apply to elements to determine when the
1282      *                stream must terminate.
1283      * @param next a function to be applied to the previous element to produce
1284      *             a new element
1285      * @return a new sequential {@code Stream}
1286      * @since 9
1287      */
1288     public static<T> Stream<T> iterate(T seed, Predicate<? super T> hasNext, UnaryOperator<T> next) {
1289         Objects.requireNonNull(next);
1290         Objects.requireNonNull(hasNext);
1291         Spliterator<T> spliterator = new Spliterators.AbstractSpliterator<>(Long.MAX_VALUE,
1292                Spliterator.ORDERED | Spliterator.IMMUTABLE) {
1293             T prev;
1294             boolean started, finished;
1295 
1296             @Override
1297             public boolean tryAdvance(Consumer<? super T> action) {
1298                 Objects.requireNonNull(action);
1299                 if (finished)
1300                     return false;
1301                 T t;
1302                 if (started)
1303                     t = next.apply(prev);
1304                 else {
1305                     t = seed;
1306                     started = true;
1307                 }
1308                 if (!hasNext.test(t)) {
1309                     prev = null;
1310                     finished = true;
1311                     return false;
1312                 }
1313                 action.accept(prev = t);
1314                 return true;
1315             }
1316 
1317             @Override
1318             public void forEachRemaining(Consumer<? super T> action) {
1319                 Objects.requireNonNull(action);
1320                 if (finished)
1321                     return;
1322                 finished = true;
1323                 T t = started ? next.apply(prev) : seed;
1324                 prev = null;
1325                 while (hasNext.test(t)) {
1326                     action.accept(t);
1327                     t = next.apply(t);
1328                 }
1329             }
1330         };
1331         return StreamSupport.stream(spliterator, false);
1332     }
1333 
1334     /**
1335      * Returns an infinite sequential unordered stream where each element is
1336      * generated by the provided {@code Supplier}.  This is suitable for
1337      * generating constant streams, streams of random elements, etc.
1338      *
1339      * @param <T> the type of stream elements
1340      * @param s the {@code Supplier} of generated elements
1341      * @return a new infinite sequential unordered {@code Stream}
1342      */
1343     public static<T> Stream<T> generate(Supplier<? extends T> s) {
1344         Objects.requireNonNull(s);
1345         return StreamSupport.stream(
1346                 new StreamSpliterators.InfiniteSupplyingSpliterator.OfRef<>(Long.MAX_VALUE, s), false);
1347     }
1348 
1349     /**
1350      * Creates a lazily concatenated stream whose elements are all the
1351      * elements of the first stream followed by all the elements of the
1352      * second stream.  The resulting stream is ordered if both
1353      * of the input streams are ordered, and parallel if either of the input
1354      * streams is parallel.  When the resulting stream is closed, the close
1355      * handlers for both input streams are invoked.
1356      *
1357      * <p>This method operates on the two input streams and binds each stream
1358      * to its source.  As a result subsequent modifications to an input stream
1359      * source may not be reflected in the concatenated stream result.
1360      *
1361      * @implNote
1362      * Use caution when constructing streams from repeated concatenation.
1363      * Accessing an element of a deeply concatenated stream can result in deep
1364      * call chains, or even {@code StackOverflowError}.
1365      *
1366      * <p>Subsequent changes to the sequential/parallel execution mode of the
1367      * returned stream are not guaranteed to be propagated to the input streams.
1368      *
1369      * @apiNote
1370      * To preserve optimization opportunities this method binds each stream to
1371      * its source and accepts only two streams as parameters.  For example, the
1372      * exact size of the concatenated stream source can be computed if the exact
1373      * size of each input stream source is known.
1374      * To concatenate more streams without binding, or without nested calls to
1375      * this method, try creating a stream of streams and flat-mapping with the
1376      * identity function, for example:
1377      * <pre>{@code
1378      *     Stream<T> concat = Stream.of(s1, s2, s3, s4).flatMap(s -> s);
1379      * }</pre>
1380      *
1381      * @param <T> The type of stream elements
1382      * @param a the first stream
1383      * @param b the second stream
1384      * @return the concatenation of the two input streams
1385      */
1386     public static <T> Stream<T> concat(Stream<? extends T> a, Stream<? extends T> b) {
1387         Objects.requireNonNull(a);
1388         Objects.requireNonNull(b);
1389 
1390         @SuppressWarnings("unchecked")
1391         Spliterator<T> split = new Streams.ConcatSpliterator.OfRef<>(
1392                 (Spliterator<T>) a.spliterator(), (Spliterator<T>) b.spliterator());
1393         Stream<T> stream = StreamSupport.stream(split, a.isParallel() || b.isParallel());
1394         return stream.onClose(Streams.composedClose(a, b));
1395     }
1396 
1397     /**
1398      * A mutable builder for a {@code Stream}.  This allows the creation of a
1399      * {@code Stream} by generating elements individually and adding them to the
1400      * {@code Builder} (without the copying overhead that comes from using
1401      * an {@code ArrayList} as a temporary buffer.)
1402      *
1403      * <p>A stream builder has a lifecycle, which starts in a building
1404      * phase, during which elements can be added, and then transitions to a built
1405      * phase, after which elements may not be added.  The built phase begins
1406      * when the {@link #build()} method is called, which creates an ordered
1407      * {@code Stream} whose elements are the elements that were added to the stream
1408      * builder, in the order they were added.
1409      *
1410      * @param <T> the type of stream elements
1411      * @see Stream#builder()
1412      * @since 1.8
1413      */
1414     public interface Builder<T> extends Consumer<T> {
1415 
1416         /**
1417          * Adds an element to the stream being built.
1418          *
1419          * @throws IllegalStateException if the builder has already transitioned to
1420          * the built state
1421          */
1422         @Override
1423         void accept(T t);
1424 
1425         /**
1426          * Adds an element to the stream being built.
1427          *
1428          * @implSpec
1429          * The default implementation behaves as if:
1430          * <pre>{@code
1431          *     accept(t)
1432          *     return this;
1433          * }</pre>
1434          *
1435          * @param t the element to add
1436          * @return {@code this} builder
1437          * @throws IllegalStateException if the builder has already transitioned to
1438          * the built state
1439          */
1440         default Builder<T> add(T t) {
1441             accept(t);
1442             return this;
1443         }
1444 
1445         /**
1446          * Builds the stream, transitioning this builder to the built state.
1447          * An {@code IllegalStateException} is thrown if there are further attempts
1448          * to operate on the builder after it has entered the built state.
1449          *
1450          * @return the built stream
1451          * @throws IllegalStateException if the builder has already transitioned to
1452          * the built state
1453          */
1454         Stream<T> build();
1455 
1456     }
1457 }
--- EOF ---