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