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