1 /*
   2  * Copyright (c) 2012, 2013, 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.charset.Charset;
  28 import java.nio.file.Files;
  29 import java.nio.file.Path;
  30 import java.util.Arrays;
  31 import java.util.Collection;
  32 import java.util.Comparator;
  33 import java.util.Iterator;
  34 import java.util.Objects;
  35 import java.util.Optional;
  36 import java.util.Spliterator;
  37 import java.util.Spliterators;
  38 import java.util.concurrent.ConcurrentHashMap;
  39 import java.util.function.BiConsumer;
  40 import java.util.function.BiFunction;
  41 import java.util.function.BinaryOperator;
  42 import java.util.function.Consumer;
  43 import java.util.function.Function;
  44 import java.util.function.IntFunction;
  45 import java.util.function.Predicate;
  46 import java.util.function.Supplier;
  47 import java.util.function.ToDoubleFunction;
  48 import java.util.function.ToIntFunction;
  49 import java.util.function.ToLongFunction;
  50 import java.util.function.UnaryOperator;
  51 
  52 /**
  53  * A sequence of elements supporting sequential and parallel aggregate
  54  * operations.  The following example illustrates an aggregate operation using
  55  * {@link Stream} and {@link IntStream}:
  56  *
  57  * <pre>{@code
  58  *     int sum = widgets.stream()
  59  *                      .filter(w -> w.getColor() == RED)
  60  *                      .mapToInt(w -> w.getWeight())
  61  *                      .sum();
  62  * }</pre>
  63  *
  64  * In this example, {@code widgets} is a {@code Collection<Widget>}.  We create
  65  * a stream of {@code Widget} objects via {@link Collection#stream Collection.stream()},
  66  * filter it to produce a stream containing only the red widgets, and then
  67  * transform it into a stream of {@code int} values representing the weight of
  68  * each red widget. Then this stream is summed to produce a total weight.
  69  *
  70  * <p>To perform a computation, stream
  71  * <a href="package-summary.html#StreamOps">operations</a> are composed into a
  72  * <em>stream pipeline</em>.  A stream pipeline consists of a source (which
  73  * might be an array, a collection, a generator function, an I/O channel,
  74  * etc), zero or more <em>intermediate operations</em> (which transform a
  75  * stream into another stream, such as {@link Stream#filter(Predicate)}), and a
  76  * <em>terminal operation</em> (which produces a result or side-effect, such
  77  * as {@link Stream#count()} or {@link Stream#forEach(Consumer)}).
  78  * Streams are lazy; computation on the source data is only performed when the
  79  * terminal operation is initiated, and source elements are consumed only
  80  * as needed.
  81  *
  82  * <p>Collections and streams, while bearing some superficial similarities,
  83  * have different goals.  Collections are primarily concerned with the efficient
  84  * management of, and access to, their elements.  By contrast, streams do not
  85  * provide a means to directly access or manipulate their elements, and are
  86  * instead concerned with declaratively describing their source and the
  87  * computational operations which will be performed in aggregate on that source.
  88  * However, if the provided stream operations do not offer the desired
  89  * functionality, the {@link #iterator()} and {@link #spliterator()} operations
  90  * can be used to perform a controlled traversal.
  91  *
  92  * <p>A stream pipeline, like the "widgets" example above, can be viewed as
  93  * a <em>query</em> on the stream source.  Unless the source was explicitly
  94  * designed for concurrent modification (such as a {@link ConcurrentHashMap}),
  95  * unpredictable or erroneous behavior may result from modifying the stream
  96  * source while it is being queried.
  97  *
  98  * <p>Most stream operations accept parameters that describe user-specified
  99  * behavior, such as the lambda expression {@code w -> w.getWeight()} passed to
 100  * {@code mapToInt} in the example above.  Such parameters are always instances
 101  * of a <a href="../function/package-summary.html">functional interface</a> such
 102  * as {@link java.util.function.Function}, and are often lambda expressions or
 103  * method references.  These parameters can never be null, should not modify the
 104  * stream source, and should be
 105  * <a href="package-summary.html#NonInterference">effectively stateless</a>
 106  * (their result should not depend on any state that might change during
 107  * execution of the stream pipeline.)
 108  *
 109  * <p>A stream should be operated on (invoking an intermediate or terminal stream
 110  * operation) only once.  This rules out, for example, "forked" streams, where
 111  * the same source feeds two or more pipelines, or multiple traversals of the
 112  * same stream.  A stream implementation may throw {@link IllegalStateException}
 113  * if it detects that the stream is being reused. However, since some stream
 114  * operations may return their receiver rather than a new stream object, it may
 115  * not be possible to detect reuse in all cases.
 116  *
 117  * <p>Streams have a {@link #close()} method and implement {@link AutoCloseable},
 118  * but nearly all stream instances do not actually need to be closed after use.
 119  * Generally, only streams whose source is an IO channel (such as those returned
 120  * by {@link Files#lines(Path, Charset)}) will require closing.  Most streams
 121  * are backed by collections, arrays, or generating functions, which require no
 122  * special resource management.  (If a stream does require closing, it can be
 123  * declared as a resource in a {@code try}-with-resources statement.)
 124  *
 125  * <p>Stream pipelines may execute either sequentially or in
 126  * <a href="package-summary.html#Parallelism">parallel</a>.  This
 127  * execution mode is a property of the stream.  Streams are created
 128  * with an initial choice of sequential or parallel execution.  (For example,
 129  * {@link Collection#stream() Collection.stream()} creates a sequential stream,
 130  * and {@link Collection#parallelStream() Collection.parallelStream()} creates
 131  * a parallel one.)  This choice of execution mode may be modified by the
 132  * {@link #sequential()} or {@link #parallel()} methods, and may be queried with
 133  * the {@link #isParallel()} method.
 134  *
 135  * @param <T> the type of the stream elements
 136  * @since 1.8
 137  * @see <a href="package-summary.html">java.util.stream</a>
 138  */
 139 public interface Stream<T> extends BaseStream<T, Stream<T>> {
 140 
 141     /**
 142      * Returns a stream consisting of the elements of this stream that match
 143      * the given predicate.
 144      *
 145      * <p>This is an <a href="package-summary.html#StreamOps">intermediate
 146      * operation</a>.
 147      *
 148      * @param predicate a <a href="package-summary.html#NonInterference">
 149      *                  non-interfering, stateless</a> predicate to apply to
 150      *                  each element to determine if it should be included
 151      * @return the new stream
 152      */
 153     Stream<T> filter(Predicate<? super T> predicate);
 154 
 155     /**
 156      * Returns a stream consisting of the results of applying the given
 157      * function to the elements of this stream.
 158      *
 159      * <p>This is an <a href="package-summary.html#StreamOps">intermediate
 160      * operation</a>.
 161      *
 162      * @param <R> The element type of the new stream
 163      * @param mapper a <a href="package-summary.html#NonInterference">
 164      *               non-interfering, stateless</a> function to apply to each
 165      *               element
 166      * @return the new stream
 167      */
 168     <R> Stream<R> map(Function<? super T, ? extends R> mapper);
 169 
 170     /**
 171      * Returns an {@code IntStream} consisting of the results of applying the
 172      * given function to the elements of this stream.
 173      *
 174      * <p>This is an <a href="package-summary.html#StreamOps">
 175      *     intermediate operation</a>.
 176      *
 177      * @param mapper a <a href="package-summary.html#NonInterference">
 178      *               non-interfering, stateless</a> function to apply to each
 179      *               element
 180      * @return the new stream
 181      */
 182     IntStream mapToInt(ToIntFunction<? super T> mapper);
 183 
 184     /**
 185      * Returns a {@code LongStream} consisting of the results of applying the
 186      * given function to the elements of this stream.
 187      *
 188      * <p>This is an <a href="package-summary.html#StreamOps">intermediate
 189      * operation</a>.
 190      *
 191      * @param mapper a <a href="package-summary.html#NonInterference">
 192      *               non-interfering, stateless</a> function to apply to each
 193      *               element
 194      * @return the new stream
 195      */
 196     LongStream mapToLong(ToLongFunction<? super T> mapper);
 197 
 198     /**
 199      * Returns a {@code DoubleStream} consisting of the results of applying the
 200      * given function to the elements of this stream.
 201      *
 202      * <p>This is an <a href="package-summary.html#StreamOps">intermediate
 203      * operation</a>.
 204      *
 205      * @param mapper a <a href="package-summary.html#NonInterference">
 206      *               non-interfering, stateless</a> function to apply to each
 207      *               element
 208      * @return the new stream
 209      */
 210     DoubleStream mapToDouble(ToDoubleFunction<? super T> mapper);
 211 
 212     /**
 213      * Returns a stream consisting of the results of replacing each element of
 214      * this stream with the contents of the stream produced by applying the
 215      * provided mapping function to each element.  (If the result of the mapping
 216      * function is {@code null}, this is treated as if the result was an empty
 217      * stream.)
 218      *
 219      * <p>This is an <a href="package-summary.html#StreamOps">intermediate
 220      * operation</a>.
 221      *
 222      * @apiNote
 223      * The {@code flatMap()} operation has the effect of applying a one-to-many
 224      * tranformation to the elements of the stream, and then flattening the
 225      * resulting elements into a new stream. For example, if {@code orders}
 226      * is a stream of purchase orders, and each purchase order contains a
 227      * collection of line items, then the following produces a stream of line
 228      * items:
 229      * <pre>{@code
 230      *     orderStream.flatMap(order -> order.getLineItems().stream())...
 231      * }</pre>
 232      *
 233      * @param <R> The element type of the new stream
 234      * @param mapper a <a href="package-summary.html#NonInterference">
 235      *               non-interfering, stateless</a> function to apply to each
 236      *               element which produces a stream of new values
 237      * @return the new stream
 238      */
 239     <R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper);
 240 
 241     /**
 242      * Returns an {@code IntStream} consisting of the results of replacing each
 243      * element of this stream with the contents of the stream produced by
 244      * applying the provided mapping function to each element.  (If the result
 245      * of the mapping function is {@code null}, this is treated as if the result
 246      * was an empty stream.)
 247      *
 248      * <p>This is an <a href="package-summary.html#StreamOps">intermediate
 249      * operation</a>.
 250      *
 251      * @param mapper a <a href="package-summary.html#NonInterference">
 252      *               non-interfering, stateless</a> function to apply to each
 253      *               element which produces a stream of new values
 254      * @return the new stream
 255      */
 256     IntStream flatMapToInt(Function<? super T, ? extends IntStream> mapper);
 257 
 258     /**
 259      * Returns a {@code LongStream} consisting of the results of replacing each
 260      * element of this stream with the contents of the stream produced
 261      * by applying the provided mapping function to each element.  (If the result
 262      * of the mapping function is {@code null}, this is treated as if the result
 263      * was an empty stream.)
 264      *
 265      * <p>This is an <a href="package-summary.html#StreamOps">intermediate
 266      * operation</a>.
 267      *
 268      * @param mapper a <a href="package-summary.html#NonInterference">
 269      *               non-interfering, stateless</a> function to apply to
 270      *               each element which produces a stream of new values
 271      * @return the new stream
 272      */
 273     LongStream flatMapToLong(Function<? super T, ? extends LongStream> mapper);
 274 
 275     /**
 276      * Returns a {@code DoubleStream} consisting of the results of replacing each
 277      * element of this stream with the contents of the stream produced
 278      * by applying the provided mapping function to each element.  (If the result
 279      * of the mapping function is {@code null}, this is treated as if the result
 280      * was an empty stream.)
 281      *
 282      * <p>This is an <a href="package-summary.html#StreamOps">intermediate
 283      * operation</a>.
 284      *
 285      * @param mapper a <a href="package-summary.html#NonInterference">
 286      *               non-interfering, stateless</a> function to apply to each
 287      *               element which produces a stream of new values
 288      * @return the new stream
 289      */
 290     DoubleStream flatMapToDouble(Function<? super T, ? extends DoubleStream> mapper);
 291 
 292     /**
 293      * Returns a stream consisting of the distinct elements (according to
 294      * {@link Object#equals(Object)}) of this stream.
 295      *
 296      * <p>This is a <a href="package-summary.html#StreamOps">stateful
 297      * intermediate operation</a>.
 298      *
 299      * @return the new stream
 300      */
 301     Stream<T> distinct();
 302 
 303     /**
 304      * Returns a stream consisting of the elements of this stream, sorted
 305      * according to natural order.  If the elements of this stream are not
 306      * {@code Comparable}, a {@code java.lang.ClassCastException} may be thrown
 307      * when the terminal operation is executed.
 308      *
 309      * <p>This is a <a href="package-summary.html#StreamOps">stateful
 310      * intermediate operation</a>.
 311      *
 312      * @return the new stream
 313      */
 314     Stream<T> sorted();
 315 
 316     /**
 317      * Returns a stream consisting of the elements of this stream, sorted
 318      * according to the provided {@code Comparator}.
 319      *
 320      * <p>This is a <a href="package-summary.html#StreamOps">stateful
 321      * intermediate operation</a>.
 322      *
 323      * @param comparator a <a href="package-summary.html#NonInterference">
 324      *                   non-interfering, stateless</a> {@code Comparator} to
 325      *                   be used to compare stream elements
 326      * @return the new stream
 327      */
 328     Stream<T> sorted(Comparator<? super T> comparator);
 329 
 330     /**
 331      * Returns a stream consisting of the elements of this stream, additionally
 332      * performing the provided action on each element as elements are consumed
 333      * from the resulting stream.
 334      *
 335      * <p>This is an <a href="package-summary.html#StreamOps">intermediate
 336      * operation</a>.
 337      *
 338      * <p>For parallel stream pipelines, the action may be called at
 339      * whatever time and in whatever thread the element is made available by the
 340      * upstream operation.  If the action modifies shared state,
 341      * it is responsible for providing the required synchronization.
 342      *
 343      * @apiNote This method exists mainly to support debugging, where you want
 344      * to see the elements as they flow past a certain point in a pipeline:
 345      * <pre>{@code
 346      *     list.stream()
 347      *         .filter(filteringFunction)
 348      *         .peek(e -> System.out.println("Filtered value: " + e));
 349      *         .map(mappingFunction)
 350      *         .peek(e -> System.out.println("Mapped value: " + e));
 351      *         .collect(Collectors.intoList());
 352      * }</pre>
 353      *
 354      * @param action a <a href="package-summary.html#NonInterference">
 355      *                 non-interfering</a> action to perform on the elements as
 356      *                 they are consumed from the stream
 357      * @return the new stream
 358      */
 359     Stream<T> peek(Consumer<? super T> action);
 360 
 361     /**
 362      * Returns a stream consisting of the elements of this stream, truncated
 363      * to be no longer than {@code maxSize} in length.
 364      *
 365      * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting
 366      * stateful intermediate operation</a>.
 367      *
 368      * @param maxSize the number of elements the stream should be limited to
 369      * @return the new stream
 370      * @throws IllegalArgumentException if {@code maxSize} is negative
 371      */
 372     Stream<T> limit(long maxSize);
 373 
 374     /**
 375      * Returns a stream consisting of the remaining elements of this stream
 376      * after discarding the first {@code startInclusive} elements of the stream.
 377      * If this stream contains fewer than {@code startInclusive} elements then an
 378      * empty stream will be returned.
 379      *
 380      * <p>This is a <a href="package-summary.html#StreamOps">stateful
 381      * intermediate operation</a>.
 382      *
 383      * @param startInclusive the number of leading elements to skip
 384      * @return the new stream
 385      * @throws IllegalArgumentException if {@code startInclusive} is negative
 386      */
 387     Stream<T> substream(long startInclusive);
 388 
 389     /**
 390      * Returns a stream consisting of the remaining elements of this stream
 391      * after discarding the first {@code startInclusive} elements and truncating
 392      * the result to be no longer than {@code endExclusive - startInclusive}
 393      * elements in length. If this stream contains fewer than
 394      * {@code startInclusive} elements then an empty stream will be returned.
 395      *
 396      * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting
 397      * stateful intermediate operation</a>.
 398      *
 399      * @param startInclusive the starting position of the substream, inclusive
 400      * @param endExclusive the ending position of the substream, exclusive
 401      * @return the new stream
 402      * @throws IllegalArgumentException if {@code startInclusive} or
 403      * {@code endExclusive} is negative or {@code startInclusive} is greater
 404      * than {@code endExclusive}
 405      */
 406     Stream<T> substream(long startInclusive, long endExclusive);
 407 
 408     /**
 409      * Performs an action for each element of this stream.
 410      *
 411      * <p>This is a <a href="package-summary.html#StreamOps">terminal
 412      * operation</a>.
 413      *
 414      * <p>For parallel stream pipelines, this operation does <em>not</em>
 415      * guarantee to respect the encounter order of the stream, as doing so
 416      * would sacrifice the benefit of parallelism.  For any given element, the
 417      * action may be performed at whatever time and in whatever thread the
 418      * library chooses.  If the action accesses shared state, it is
 419      * responsible for providing the required synchronization.
 420      *
 421      * @param action a <a href="package-summary.html#NonInterference">
 422      *               non-interfering</a> action to perform on the elements
 423      */
 424     void forEach(Consumer<? super T> action);
 425 
 426     /**
 427      * Performs an action for each element of this stream, guaranteeing that
 428      * each element is processed in encounter order for streams that have a
 429      * defined encounter order.
 430      *
 431      * <p>This is a <a href="package-summary.html#StreamOps">terminal
 432      * operation</a>.
 433      *
 434      * @param action a <a href="package-summary.html#NonInterference">
 435      *               non-interfering</a> action to perform on the elements
 436      * @see #forEach(Consumer)
 437      */
 438     void forEachOrdered(Consumer<? super T> action);
 439 
 440     /**
 441      * Returns an array containing the elements of this stream.
 442      *
 443      * <p>This is a <a href="package-summary.html#StreamOps">terminal
 444      * operation</a>.
 445      *
 446      * @return an array containing the elements of this stream
 447      */
 448     Object[] toArray();
 449 
 450     /**
 451      * Returns an array containing the elements of this stream, using the
 452      * provided {@code generator} function to allocate the returned array, as
 453      * well as any additional arrays that might be required for a partitioned
 454      * execution or for resizing.
 455      *
 456      * <p>This is a <a href="package-summary.html#StreamOps">terminal
 457      * operation</a>.
 458      *
 459      * @apiNote
 460      * The generator function takes an integer, which is the size of the
 461      * desired array, and produces an array of the desired size.  This can be
 462      * concisely expressed with an array constructor reference:
 463      * <pre>{@code
 464      *     Person[] men = people.stream()
 465      *                          .filter(p -> p.getGender() == MALE)
 466      *                          .toArray(Person[]::new);
 467      * }</pre>
 468      *
 469      * @param <A> the element type of the resulting array
 470      * @param generator a function which produces a new array of the desired
 471      *                  type and the provided length
 472      * @return an array containing the elements in this stream
 473      * @throws ArrayStoreException if the runtime type of the array returned
 474      * from the array generator is not a supertype of the runtime type of every
 475      * element in this stream
 476      */
 477     <A> A[] toArray(IntFunction<A[]> generator);
 478 
 479     /**
 480      * Performs a <a href="package-summary.html#Reduction">reduction</a> on the
 481      * elements of this stream, using the provided identity value and an
 482      * <a href="package-summary.html#Associativity">associative</a>
 483      * accumulation function, and returns the reduced value.  This is equivalent
 484      * to:
 485      * <pre>{@code
 486      *     T result = identity;
 487      *     for (T element : this stream)
 488      *         result = accumulator.apply(result, element)
 489      *     return result;
 490      * }</pre>
 491      *
 492      * but is not constrained to execute sequentially.
 493      *
 494      * <p>The {@code identity} value must be an identity for the accumulator
 495      * function. This means that for all {@code t},
 496      * {@code accumulator.apply(identity, t)} is equal to {@code t}.
 497      * The {@code accumulator} function must be an
 498      * <a href="package-summary.html#Associativity">associative</a> function.
 499      *
 500      * <p>This is a <a href="package-summary.html#StreamOps">terminal
 501      * operation</a>.
 502      *
 503      * @apiNote Sum, min, max, average, and string concatenation are all special
 504      * cases of reduction. Summing a stream of numbers can be expressed as:
 505      *
 506      * <pre>{@code
 507      *     Integer sum = integers.reduce(0, (a, b) -> a+b);
 508      * }</pre>
 509      *
 510      * or:
 511      *
 512      * <pre>{@code
 513      *     Integer sum = integers.reduce(0, Integer::sum);
 514      * }</pre>
 515      *
 516      * <p>While this may seem a more roundabout way to perform an aggregation
 517      * compared to simply mutating a running total in a loop, reduction
 518      * operations parallelize more gracefully, without needing additional
 519      * synchronization and with greatly reduced risk of data races.
 520      *
 521      * @param identity the identity value for the accumulating function
 522      * @param accumulator an <a href="package-summary.html#Associativity">associative</a>
 523      *                    <a href="package-summary.html#NonInterference">non-interfering,
 524      *                    stateless</a> function for combining two values
 525      * @return the result of the reduction
 526      */
 527     T reduce(T identity, BinaryOperator<T> accumulator);
 528 
 529     /**
 530      * Performs a <a href="package-summary.html#Reduction">reduction</a> on the
 531      * elements of this stream, using an
 532      * <a href="package-summary.html#Associativity">associative</a> accumulation
 533      * function, and returns an {@code Optional} describing the reduced value,
 534      * if any. This is equivalent to:
 535      * <pre>{@code
 536      *     boolean foundAny = false;
 537      *     T result = null;
 538      *     for (T element : this stream) {
 539      *         if (!foundAny) {
 540      *             foundAny = true;
 541      *             result = element;
 542      *         }
 543      *         else
 544      *             result = accumulator.apply(result, element);
 545      *     }
 546      *     return foundAny ? Optional.of(result) : Optional.empty();
 547      * }</pre>
 548      *
 549      * but is not constrained to execute sequentially.
 550      *
 551      * <p>The {@code accumulator} function must be an
 552      * <a href="package-summary.html#Associativity">associative</a> function.
 553      *
 554      * <p>This is a <a href="package-summary.html#StreamOps">terminal
 555      * operation</a>.
 556      *
 557      * @param accumulator an <a href="package-summary.html#Associativity">associative</a>
 558      *                    <a href="package-summary.html#NonInterference">non-interfering,
 559      *                    stateless</a> function for combining two values
 560      * @return an {@link Optional} describing the result of the reduction
 561      * @throws NullPointerException if the result of the reduction is null
 562      * @see #reduce(Object, BinaryOperator)
 563      * @see #min(java.util.Comparator)
 564      * @see #max(java.util.Comparator)
 565      */
 566     Optional<T> reduce(BinaryOperator<T> accumulator);
 567 
 568     /**
 569      * Performs a <a href="package-summary.html#Reduction">reduction</a> on the
 570      * elements of this stream, using the provided identity, accumulation and
 571      * combining functions.  This is equivalent to:
 572      * <pre>{@code
 573      *     U result = identity;
 574      *     for (T element : this stream)
 575      *         result = accumulator.apply(result, element)
 576      *     return result;
 577      * }</pre>
 578      *
 579      * but is not constrained to execute sequentially.
 580      *
 581      * <p>The {@code identity} value must be an identity for the combiner
 582      * function.  This means that for all {@code u}, {@code combiner(identity, u)}
 583      * is equal to {@code u}.  Additionally, the {@code combiner} function
 584      * must be compatible with the {@code accumulator} function; for all
 585      * {@code u} and {@code t}, the following must hold:
 586      * <pre>{@code
 587      *     combiner.apply(u, accumulator.apply(identity, t)) == accumulator.apply(u, t)
 588      * }</pre>
 589      *
 590      * <p>This is a <a href="package-summary.html#StreamOps">terminal
 591      * operation</a>.
 592      *
 593      * @apiNote Many reductions using this form can be represented more simply
 594      * by an explicit combination of {@code map} and {@code reduce} operations.
 595      * The {@code accumulator} function acts as a fused mapper and accumulator,
 596      * which can sometimes be more efficient than separate mapping and reduction,
 597      * such as when knowing the previously reduced value allows you to avoid
 598      * some computation.
 599      *
 600      * @param <U> The type of the result
 601      * @param identity the identity value for the combiner function
 602      * @param accumulator an <a href="package-summary.html#Associativity">associative</a>
 603      *                    <a href="package-summary.html#NonInterference">non-interfering,
 604      *                    stateless</a> function for incorporating an additional
 605      *                    element into a result
 606      * @param combiner an <a href="package-summary.html#Associativity">associative</a>
 607      *                 <a href="package-summary.html#NonInterference">non-interfering,
 608      *                 stateless</a> function for combining two values, which
 609      *                 must be compatible with the accumulator function
 610      * @return the result of the reduction
 611      * @see #reduce(BinaryOperator)
 612      * @see #reduce(Object, BinaryOperator)
 613      */
 614     <U> U reduce(U identity,
 615                  BiFunction<U, ? super T, U> accumulator,
 616                  BinaryOperator<U> combiner);
 617 
 618     /**
 619      * Performs a <a href="package-summary.html#MutableReduction">mutable
 620      * reduction</a> operation on the elements of this stream.  A mutable
 621      * reduction is one in which the reduced value is a mutable result container,
 622      * such as an {@code ArrayList}, and elements are incorporated by updating
 623      * the state of the result rather than by replacing the result.  This
 624      * produces a result equivalent to:
 625      * <pre>{@code
 626      *     R result = supplier.get();
 627      *     for (T element : this stream)
 628      *         accumulator.accept(result, element);
 629      *     return result;
 630      * }</pre>
 631      *
 632      * <p>Like {@link #reduce(Object, BinaryOperator)}, {@code collect} operations
 633      * can be parallelized without requiring additional synchronization.
 634      *
 635      * <p>This is a <a href="package-summary.html#StreamOps">terminal
 636      * operation</a>.
 637      *
 638      * @apiNote There are many existing classes in the JDK whose signatures are
 639      * well-suited for use with method references as arguments to {@code collect()}.
 640      * For example, the following will accumulate strings into an {@code ArrayList}:
 641      * <pre>{@code
 642      *     List<String> asList = stringStream.collect(ArrayList::new, ArrayList::add,
 643      *                                                ArrayList::addAll);
 644      * }</pre>
 645      *
 646      * <p>The following will take a stream of strings and concatenates them into a
 647      * single string:
 648      * <pre>{@code
 649      *     String concat = stringStream.collect(StringBuilder::new, StringBuilder::append,
 650      *                                          StringBuilder::append)
 651      *                                 .toString();
 652      * }</pre>
 653      *
 654      * @param <R> type of the result
 655      * @param supplier a function that creates a new result container. For a
 656      *                 parallel execution, this function may be called
 657      *                 multiple times and must return a fresh value each time.
 658      * @param accumulator an <a href="package-summary.html#Associativity">associative</a>
 659      *                    <a href="package-summary.html#NonInterference">non-interfering,
 660      *                    stateless</a> function for incorporating an additional
 661      *                    element into a result
 662      * @param combiner an <a href="package-summary.html#Associativity">associative</a>
 663      *                 <a href="package-summary.html#NonInterference">non-interfering,
 664      *                 stateless</a> function for combining two values, which
 665      *                 must be compatible with the accumulator function
 666      * @return the result of the reduction
 667      */
 668     <R> R collect(Supplier<R> supplier,
 669                   BiConsumer<R, ? super T> accumulator,
 670                   BiConsumer<R, R> combiner);
 671 
 672     /**
 673      * Performs a <a href="package-summary.html#MutableReduction">mutable
 674      * reduction</a> operation on the elements of this stream using a
 675      * {@code Collector}.  A {@code Collector}
 676      * encapsulates the functions used as arguments to
 677      * {@link #collect(Supplier, BiConsumer, BiConsumer)}, allowing for reuse of
 678      * collection strategies and composition of collect operations such as
 679      * multiple-level grouping or partitioning.
 680      *
 681      * <p>This is a <a href="package-summary.html#StreamOps">terminal
 682      * operation</a>.
 683      *
 684      * <p>When executed in parallel, multiple intermediate results may be
 685      * instantiated, populated, and merged so as to maintain isolation of
 686      * mutable data structures.  Therefore, even when executed in parallel
 687      * with non-thread-safe data structures (such as {@code ArrayList}), no
 688      * additional synchronization is needed for a parallel reduction.
 689      *
 690      * @apiNote
 691      * The following will accumulate strings into an ArrayList:
 692      * <pre>{@code
 693      *     List<String> asList = stringStream.collect(Collectors.toList());
 694      * }</pre>
 695      *
 696      * <p>The following will classify {@code Person} objects by city:
 697      * <pre>{@code
 698      *     Map<String, List<Person>> peopleByCity
 699      *         = personStream.collect(Collectors.groupingBy(Person::getCity));
 700      * }</pre>
 701      *
 702      * <p>The following will classify {@code Person} objects by state and city,
 703      * cascading two {@code Collector}s together:
 704      * <pre>{@code
 705      *     Map<String, Map<String, List<Person>>> peopleByStateAndCity
 706      *         = personStream.collect(Collectors.groupingBy(Person::getState,
 707      *                                                      Collectors.groupingBy(Person::getCity)));
 708      * }</pre>
 709      *
 710      * @param <R> the type of the result
 711      * @param <A> the intermediate accumulation type of the {@code Collector}
 712      * @param collector the {@code Collector} describing the reduction
 713      * @return the result of the reduction
 714      * @see #collect(Supplier, BiConsumer, BiConsumer)
 715      * @see Collectors
 716      */
 717     <R, A> R collect(Collector<? super T, A, R> collector);
 718 
 719     /**
 720      * Returns the minimum element of this stream according to the provided
 721      * {@code Comparator}.  This is a special case of a
 722      * <a href="package-summary.html#Reduction">reduction</a>.
 723      *
 724      * <p>This is a <a href="package-summary.html#StreamOps">terminal operation</a>.
 725      *
 726      * @param comparator a <a href="package-summary.html#NonInterference">non-interfering,
 727      *                   stateless</a> {@code Comparator} to use to compare
 728      *                   elements of this stream
 729      * @return an {@code Optional} describing the minimum element of this stream,
 730      * or an empty {@code Optional} if the stream is empty
 731      * @throws NullPointerException if the minimum element is null
 732      */
 733     Optional<T> min(Comparator<? super T> comparator);
 734 
 735     /**
 736      * Returns the maximum element of this stream according to the provided
 737      * {@code Comparator}.  This is a special case of a
 738      * <a href="package-summary.html#Reduction">reduction</a>.
 739      *
 740      * <p>This is a <a href="package-summary.html#StreamOps">terminal
 741      * operation</a>.
 742      *
 743      * @param comparator a <a href="package-summary.html#NonInterference">non-interfering,
 744      *                   stateless</a> {@code Comparator} to use to compare
 745      *                   elements of this stream
 746      * @return an {@code Optional} describing the maximum element of this stream,
 747      * or an empty {@code Optional} if the stream is empty
 748      * @throws NullPointerException if the maximum element is null
 749      */
 750     Optional<T> max(Comparator<? super T> comparator);
 751 
 752     /**
 753      * Returns the count of elements in this stream.  This is a special case of
 754      * a <a href="package-summary.html#Reduction">reduction</a> and is
 755      * equivalent to:
 756      * <pre>{@code
 757      *     return mapToLong(e -> 1L).sum();
 758      * }</pre>
 759      *
 760      * <p>This is a <a href="package-summary.html#StreamOps">terminal operation</a>.
 761      *
 762      * @return the count of elements in this stream
 763      */
 764     long count();
 765 
 766     /**
 767      * Returns whether any elements of this stream match the provided
 768      * predicate.  May not evaluate the predicate on all elements if not
 769      * necessary for determining the result.
 770      *
 771      * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting
 772      * terminal operation</a>.
 773      *
 774      * @param predicate a <a href="package-summary.html#NonInterference">non-interfering,
 775      *                  stateless</a> predicate to apply to elements of this
 776      *                  stream
 777      * @return {@code true} if any elements of the stream match the provided
 778      * predicate otherwise {@code false}
 779      */
 780     boolean anyMatch(Predicate<? super T> predicate);
 781 
 782     /**
 783      * Returns whether all elements of this stream match the provided predicate.
 784      * May not evaluate the predicate on all elements if not necessary for
 785      * determining the result.
 786      *
 787      * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting
 788      * terminal operation</a>.
 789      *
 790      * @param predicate a <a href="package-summary.html#NonInterference">non-interfering,
 791      *                  stateless</a> predicate to apply to elements of this
 792      *                  stream
 793      * @return {@code true} if all elements of the stream match the provided
 794      * predicate otherwise {@code false}
 795      */
 796     boolean allMatch(Predicate<? super T> predicate);
 797 
 798     /**
 799      * Returns whether no elements of this stream match the provided predicate.
 800      * May not evaluate the predicate on all elements if not necessary for
 801      * determining the result.
 802      *
 803      * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting
 804      * terminal operation</a>.
 805      *
 806      * @param predicate a <a href="package-summary.html#NonInterference">non-interfering,
 807      *                  stateless</a> predicate to apply to elements of this
 808      *                  stream
 809      * @return {@code true} if no elements of the stream match the provided
 810      * predicate otherwise {@code false}
 811      */
 812     boolean noneMatch(Predicate<? super T> predicate);
 813 
 814     /**
 815      * Returns an {@link Optional} describing the first element of this stream,
 816      * or an empty {@code Optional} if the stream is empty.  If the stream has
 817      * no encounter order, then any element may be returned.
 818      *
 819      * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting
 820      * terminal operation</a>.
 821      *
 822      * @return an {@code Optional} describing the first element of this stream,
 823      * or an empty {@code Optional} if the stream is empty
 824      * @throws NullPointerException if the element selected is null
 825      */
 826     Optional<T> findFirst();
 827 
 828     /**
 829      * Returns an {@link Optional} describing some element of the stream, or an
 830      * empty {@code Optional} if the stream is empty.
 831      *
 832      * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting
 833      * terminal operation</a>.
 834      *
 835      * <p>The behavior of this operation is explicitly nondeterministic; it is
 836      * free to select any element in the stream.  This is to allow for maximal
 837      * performance in parallel operations; the cost is that multiple invocations
 838      * on the same source may not return the same result.  (If a stable result
 839      * is desired, use {@link #findFirst()} instead.)
 840      *
 841      * @return an {@code Optional} describing some element of this stream, or an
 842      * empty {@code Optional} if the stream is empty
 843      * @throws NullPointerException if the element selected is null
 844      * @see #findFirst()
 845      */
 846     Optional<T> findAny();
 847 
 848     // Static factories
 849 
 850     /**
 851      * Returns a builder for a {@code Stream}.
 852      *
 853      * @param <T> type of elements
 854      * @return a stream builder
 855      */
 856     public static<T> Builder<T> builder() {
 857         return new Streams.StreamBuilderImpl<>();
 858     }
 859 
 860     /**
 861      * Returns an empty sequential {@code Stream}.
 862      *
 863      * @param <T> the type of stream elements
 864      * @return an empty sequential stream
 865      */
 866     public static<T> Stream<T> empty() {
 867         return StreamSupport.stream(Spliterators.<T>emptySpliterator(), false);
 868     }
 869 
 870     /**
 871      * Returns a sequential {@code Stream} containing a single element.
 872      *
 873      * @param t the single element
 874      * @param <T> the type of stream elements
 875      * @return a singleton sequential stream
 876      */
 877     public static<T> Stream<T> of(T t) {
 878         return StreamSupport.stream(new Streams.StreamBuilderImpl<>(t), false);
 879     }
 880 
 881     /**
 882      * Returns a sequential ordered stream whose elements are the specified values.
 883      *
 884      * @param <T> the type of stream elements
 885      * @param values the elements of the new stream
 886      * @return the new stream
 887      */
 888     @SafeVarargs
 889     @SuppressWarnings("varargs") // Creating a stream from an array is safe
 890     public static<T> Stream<T> of(T... values) {
 891         return Arrays.stream(values);
 892     }
 893 
 894     /**
 895      * Returns an infinite sequential ordered {@code Stream} produced by iterative
 896      * application of a function {@code f} to an initial element {@code seed},
 897      * producing a {@code Stream} consisting of {@code seed}, {@code f(seed)},
 898      * {@code f(f(seed))}, etc.
 899      *
 900      * <p>The first element (position {@code 0}) in the {@code Stream} will be
 901      * the provided {@code seed}.  For {@code n > 0}, the element at position
 902      * {@code n}, will be the result of applying the function {@code f} to the
 903      * element at position {@code n - 1}.
 904      *
 905      * @param <T> the type of stream elements
 906      * @param seed the initial element
 907      * @param f a function to be applied to to the previous element to produce
 908      *          a new element
 909      * @return a new sequential {@code Stream}
 910      */
 911     public static<T> Stream<T> iterate(final T seed, final UnaryOperator<T> f) {
 912         Objects.requireNonNull(f);
 913         final Iterator<T> iterator = new Iterator<T>() {
 914             @SuppressWarnings("unchecked")
 915             T t = (T) Streams.NONE;
 916 
 917             @Override
 918             public boolean hasNext() {
 919                 return true;
 920             }
 921 
 922             @Override
 923             public T next() {
 924                 return t = (t == Streams.NONE) ? seed : f.apply(t);
 925             }
 926         };
 927         return StreamSupport.stream(Spliterators.spliteratorUnknownSize(
 928                 iterator,
 929                 Spliterator.ORDERED | Spliterator.IMMUTABLE), false);
 930     }
 931 
 932     /**
 933      * Returns a sequential stream where each element is generated by
 934      * the provided {@code Supplier}.  This is suitable for generating
 935      * constant streams, streams of random elements, etc.
 936      *
 937      * @param <T> the type of stream elements
 938      * @param s the {@code Supplier} of generated elements
 939      * @return a new sequential {@code Stream}
 940      */
 941     public static<T> Stream<T> generate(Supplier<T> s) {
 942         Objects.requireNonNull(s);
 943         return StreamSupport.stream(
 944                 new StreamSpliterators.InfiniteSupplyingSpliterator.OfRef<>(Long.MAX_VALUE, s), false);
 945     }
 946 
 947     /**
 948      * Creates a lazily concatenated stream whose elements are all the
 949      * elements of the first stream followed by all the elements of the
 950      * second stream. The resulting stream is ordered if both
 951      * of the input streams are ordered, and parallel if either of the input
 952      * streams is parallel.  When the resulting stream is closed, the close
 953      * handlers for both input streams are invoked.
 954      *
 955      * @param <T> The type of stream elements
 956      * @param a the first stream
 957      * @param b the second stream
 958      * @return the concatenation of the two input streams
 959      */
 960     public static <T> Stream<T> concat(Stream<? extends T> a, Stream<? extends T> b) {
 961         Objects.requireNonNull(a);
 962         Objects.requireNonNull(b);
 963 
 964         @SuppressWarnings("unchecked")
 965         Spliterator<T> split = new Streams.ConcatSpliterator.OfRef<>(
 966                 (Spliterator<T>) a.spliterator(), (Spliterator<T>) b.spliterator());
 967         Stream<T> stream = StreamSupport.stream(split, a.isParallel() || b.isParallel());
 968         return stream.onClose(Streams.composedClose(a, b));
 969     }
 970 
 971     /**
 972      * A mutable builder for a {@code Stream}.  This allows the creation of a
 973      * {@code Stream} by generating elements individually and adding them to the
 974      * {@code Builder} (without the copying overhead that comes from using
 975      * an {@code ArrayList} as a temporary buffer.)
 976      *
 977      * <p>A stream builder has a lifecycle, which starts in a building
 978      * phase, during which elements can be added, and then transitions to a built
 979      * phase, after which elements may not be added.  The built phase begins
 980      * when the {@link #build()} method is called, which creates an ordered
 981      * {@code Stream} whose elements are the elements that were added to the stream
 982      * builder, in the order they were added.
 983      *
 984      * @param <T> the type of stream elements
 985      * @see Stream#builder()
 986      * @since 1.8
 987      */
 988     public interface Builder<T> extends Consumer<T> {
 989 
 990         /**
 991          * Adds an element to the stream being built.
 992          *
 993          * @throws IllegalStateException if the builder has already transitioned to
 994          * the built state
 995          */
 996         @Override
 997         void accept(T t);
 998 
 999         /**
1000          * Adds an element to the stream being built.
1001          *
1002          * @implSpec
1003          * The default implementation behaves as if:
1004          * <pre>{@code
1005          *     accept(t)
1006          *     return this;
1007          * }</pre>
1008          *
1009          * @param t the element to add
1010          * @return {@code this} builder
1011          * @throws IllegalStateException if the builder has already transitioned to
1012          * the built state
1013          */
1014         default Builder<T> add(T t) {
1015             accept(t);
1016             return this;
1017         }
1018 
1019         /**
1020          * Builds the stream, transitioning this builder to the built state.
1021          * An {@code IllegalStateException} is thrown if there are further attempts
1022          * to operate on the builder after it has entered the built state.
1023          *
1024          * @return the built stream
1025          * @throws IllegalStateException if the builder has already transitioned to
1026          * the built state
1027          */
1028         Stream<T> build();
1029 
1030     }
1031 }