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.IntSummaryStatistics;
  33 import java.util.Objects;
  34 import java.util.OptionalDouble;
  35 import java.util.OptionalInt;
  36 import java.util.PrimitiveIterator;
  37 import java.util.Spliterator;
  38 import java.util.Spliterators;
  39 import java.util.concurrent.ConcurrentHashMap;
  40 import java.util.function.BiConsumer;
  41 import java.util.function.Function;
  42 import java.util.function.IntBinaryOperator;
  43 import java.util.function.IntConsumer;
  44 import java.util.function.IntFunction;
  45 import java.util.function.IntPredicate;
  46 import java.util.function.IntSupplier;
  47 import java.util.function.IntToDoubleFunction;
  48 import java.util.function.IntToLongFunction;
  49 import java.util.function.IntUnaryOperator;
  50 import java.util.function.ObjIntConsumer;
  51 import java.util.function.Supplier;
  52 
  53 /**
  54  * A sequence of elements supporting sequential and parallel aggregate
  55  * operations.  The following example illustrates an aggregate operation using
  56  * {@link Stream} and {@link IntStream}:
  57  *
  58  * <pre>{@code
  59  *     int sum = widgets.stream()
  60  *                      .filter(w -> w.getColor() == RED)
  61  *                      .mapToInt(w -> w.getWeight())
  62  *                      .sum();
  63  * }</pre>
  64  *
  65  * In this example, {@code widgets} is a {@code Collection<Widget>}.  We create
  66  * a stream of {@code Widget} objects via {@link Collection#stream Collection.stream()},
  67  * filter it to produce a stream containing only the red widgets, and then
  68  * transform it into a stream of {@code int} values representing the weight of
  69  * each red widget. Then this stream is summed to produce a total weight.
  70  *
  71  * <p>To perform a computation, stream
  72  * <a href="package-summary.html#StreamOps">operations</a> are composed into a
  73  * <em>stream pipeline</em>.  A stream pipeline consists of a source (which
  74  * might be an array, a collection, a generator function, an IO channel,
  75  * etc), zero or more <em>intermediate operations</em> (which transform a
  76  * stream into another stream, such as {@link IntStream#filter(IntPredicate)}), and a
  77  * <em>terminal operation</em> (which produces a result or side-effect, such
  78  * as {@link IntStream#sum()} or {@link IntStream#forEach(IntConsumer)}).
  79  * Streams are lazy; computation on the source data is only performed when the
  80  * terminal operation is initiated, and source elements are consumed only
  81  * as needed.
  82  *
  83  * <p>Collections and streams, while bearing some superficial similarities,
  84  * have different goals.  Collections are primarily concerned with the efficient
  85  * management of, and access to, their elements.  By contrast, streams do not
  86  * provide a means to directly access or manipulate their elements, and are
  87  * instead concerned with declaratively describing their source and the
  88  * computational operations which will be performed in aggregate on that source.
  89  * However, if the provided stream operations do not offer the desired
  90  * functionality, the {@link #iterator()} and {@link #spliterator()} operations
  91  * can be used to perform a controlled traversal.
  92  *
  93  * <p>A stream pipeline, like the "widgets" example above, can be viewed as
  94  * a <em>query</em> on the stream source.  Unless the source was explicitly
  95  * designed for concurrent modification (such as a {@link ConcurrentHashMap}),
  96  * unpredictable or erroneous behavior may result from modifying the stream
  97  * source while it is being queried.
  98  *
  99  * <p>Most stream operations accept parameters that describe user-specified
 100  * behavior, such as the lambda expression {@code w -> w.getWeight()} passed to
 101  * {@code mapToInt} in the example above.  Such parameters are always instances
 102  * of a <a href="../function/package-summary.html">functional interface</a> such
 103  * as {@link java.util.function.Function}, and are often lambda expressions or
 104  * method references.  These parameters can never be null, should not modify the
 105  * stream source, and should be
 106  * <a href="package-summary.html#NonInterference">effectively stateless</a>
 107  * (their result should not depend on any state that might change during
 108  * execution of the stream pipeline.)
 109  *
 110  * <p>A stream should be operated on (invoking an intermediate or terminal stream
 111  * operation) only once.  This rules out, for example, "forked" streams, where
 112  * the same source feeds two or more pipelines, or multiple traversals of the
 113  * same stream.  A stream implementation may throw {@link IllegalStateException}
 114  * if it detects that the stream is being reused. However, since some stream
 115  * operations may return their receiver rather than a new stream object, it may
 116  * not be possible to detect reuse in all cases.
 117  *
 118  * <p>Streams have a {@link #close()} method and implement {@link AutoCloseable},
 119  * but nearly all stream instances do not actually need to be closed after use.
 120  * Generally, only streams whose source is an IO channel (such as those returned
 121  * by {@link Files#lines(Path, Charset)}) will require closing.  Most streams
 122  * are backed by collections, arrays, or generating functions, which require no
 123  * special resource management.  (If a stream does require closing, it can be
 124  * declared as a resource in a {@code try}-with-resources statement.)
 125  *
 126  * <p>Stream pipelines may execute either sequentially or in
 127  * <a href="package-summary.html#Parallelism">parallel</a>.  This
 128  * execution mode is a property of the stream.  Streams are created
 129  * with an initial choice of sequential or parallel execution.  (For example,
 130  * {@link Collection#stream() Collection.stream()} creates a sequential stream,
 131  * and {@link Collection#parallelStream() Collection.parallelStream()} creates
 132  * a parallel one.)  This choice of execution mode may be modified by the
 133  * {@link #sequential()} or {@link #parallel()} methods, and may be queried with
 134  * the {@link #isParallel()} method.
 135  *
 136  * @since 1.8
 137  * @see <a href="package-summary.html">java.util.stream</a>
 138  */
 139 public interface IntStream extends BaseStream<Integer, IntStream> {
 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     IntStream filter(IntPredicate 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 mapper a <a href="package-summary.html#NonInterference">
 163      *               non-interfering, stateless</a> function to apply to each
 164      *               element
 165      * @return the new stream
 166      */
 167     IntStream map(IntUnaryOperator mapper);
 168 
 169     /**
 170      * Returns an object-valued {@code Stream} consisting of the results of
 171      * applying the given function to the elements of this stream.
 172      *
 173      * <p>This is an <a href="package-summary.html#StreamOps">
 174      *     intermediate operation</a>.
 175      *
 176      * @param <U> the element type of the new stream
 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     <U> Stream<U> mapToObj(IntFunction<? extends U> 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(IntToLongFunction 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(IntToDoubleFunction 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      * @param mapper a <a href="package-summary.html#NonInterference">
 223      *               non-interfering, stateless</a> function to apply to
 224      *               each element which produces an {@code IntStream} of new
 225      *               values
 226      * @return the new stream
 227      * @see Stream#flatMap(Function)
 228      */
 229     IntStream flatMap(IntFunction<? extends IntStream> mapper);
 230 
 231     /**
 232      * Returns a stream consisting of the distinct elements of this stream.
 233      *
 234      * <p>This is a <a href="package-summary.html#StreamOps">stateful
 235      * intermediate operation</a>.
 236      *
 237      * @return the new stream
 238      */
 239     IntStream distinct();
 240 
 241     /**
 242      * Returns a stream consisting of the elements of this stream in sorted
 243      * order.
 244      *
 245      * <p>This is a <a href="package-summary.html#StreamOps">stateful
 246      * intermediate operation</a>.
 247      *
 248      * @return the new stream
 249      */
 250     IntStream sorted();
 251 
 252     /**
 253      * Returns a stream consisting of the elements of this stream, additionally
 254      * performing the provided action on each element as elements are consumed
 255      * from the resulting stream.
 256      *
 257      * <p>This is an <a href="package-summary.html#StreamOps">intermediate
 258      * operation</a>.
 259      *
 260      * <p>For parallel stream pipelines, the action may be called at
 261      * whatever time and in whatever thread the element is made available by the
 262      * upstream operation.  If the action modifies shared state,
 263      * it is responsible for providing the required synchronization.
 264      *
 265      * @apiNote This method exists mainly to support debugging, where you want
 266      * to see the elements as they flow past a certain point in a pipeline:
 267      * <pre>{@code
 268      *     list.stream()
 269      *         .filter(filteringFunction)
 270      *         .peek(e -> System.out.println("Filtered value: " + e));
 271      *         .map(mappingFunction)
 272      *         .peek(e -> System.out.println("Mapped value: " + e));
 273      *         .collect(Collectors.toIntSummaryStastistics());
 274      * }</pre>
 275      *
 276      * @param action a <a href="package-summary.html#NonInterference">
 277      *               non-interfering</a> action to perform on the elements as
 278      *               they are consumed from the stream
 279      * @return the new stream
 280      */
 281     IntStream peek(IntConsumer action);
 282 
 283     /**
 284      * Returns a stream consisting of the elements of this stream, truncated
 285      * to be no longer than {@code maxSize} in length.
 286      *
 287      * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting
 288      * stateful intermediate operation</a>.
 289      *
 290      * @apiNote
 291      * While {@code limit()} is generally a cheap operation on sequential
 292      * stream pipelines, it can be quite expensive on ordered parallel pipelines,
 293      * especially for large values of {@code maxSize}, since {@code limit(n)}
 294      * is constrained to return not just any <em>n</em> elements, but the
 295      * <em>first n</em> elements in the encounter order.  Using an unordered
 296      * stream source (such as {@link #generate(IntSupplier)}) or removing the
 297      * ordering constraint with {@link #unordered()} may result in significant
 298      * speedups of {@code limit()} in parallel pipelines, if the semantics of
 299      * your situation permit.  If consistency with encounter order is required,
 300      * and you are experiencing poor performance or memory utilization with
 301      * {@code limit()} in parallel pipelines, switching to sequential execution
 302      * with {@link #sequential()} may improve performance.
 303      *
 304      * @param maxSize the number of elements the stream should be limited to
 305      * @return the new stream
 306      * @throws IllegalArgumentException if {@code maxSize} is negative
 307      */
 308     IntStream limit(long maxSize);
 309 
 310     /**
 311      * Returns a stream consisting of the remaining elements of this stream
 312      * after discarding the first {@code n} elements of the stream.
 313      * If this stream contains fewer than {@code n} elements then an
 314      * empty stream will be returned.
 315      *
 316      * <p>This is a <a href="package-summary.html#StreamOps">stateful
 317      * intermediate operation</a>.
 318      *
 319      * @apiNote
 320      * While {@code skip()} is generally a cheap operation on sequential
 321      * stream pipelines, it can be quite expensive on ordered parallel pipelines,
 322      * especially for large values of {@code n}, since {@code skip(n)}
 323      * is constrained to skip not just any <em>n</em> elements, but the
 324      * <em>first n</em> elements in the encounter order.  Using an unordered
 325      * stream source (such as {@link #generate(Supplier)}) or removing the
 326      * ordering constraint with {@link #unordered()} may result in significant
 327      * speedups of {@code skip()} in parallel pipelines, if the semantics of
 328      * your situation permit.  If consistency with encounter order is required,
 329      * and you are experiencing poor performance or memory utilization with
 330      * {@code skip()} in parallel pipelines, switching to sequential execution
 331      * with {@link #sequential()} may improve performance.
 332      *
 333      * @param n the number of leading elements to skip
 334      * @return the new stream
 335      * @throws IllegalArgumentException if {@code n} is negative
 336      */
 337     IntStream skip(long n);
 338 
 339     /**
 340      * Performs an action for each element of this stream.
 341      *
 342      * <p>This is a <a href="package-summary.html#StreamOps">terminal
 343      * operation</a>.
 344      *
 345      * <p>For parallel stream pipelines, this operation does <em>not</em>
 346      * guarantee to respect the encounter order of the stream, as doing so
 347      * would sacrifice the benefit of parallelism.  For any given element, the
 348      * action may be performed at whatever time and in whatever thread the
 349      * library chooses.  If the action accesses shared state, it is
 350      * responsible for providing the required synchronization.
 351      *
 352      * @param action a <a href="package-summary.html#NonInterference">
 353      *               non-interfering</a> action to perform on the elements
 354      */
 355     void forEach(IntConsumer action);
 356 
 357     /**
 358      * Performs an action for each element of this stream, guaranteeing that
 359      * each element is processed in encounter order for streams that have a
 360      * defined encounter order.
 361      *
 362      * <p>This is a <a href="package-summary.html#StreamOps">terminal
 363      * operation</a>.
 364      *
 365      * @param action a <a href="package-summary.html#NonInterference">
 366      *               non-interfering</a> action to perform on the elements
 367      * @see #forEach(IntConsumer)
 368      */
 369     void forEachOrdered(IntConsumer action);
 370 
 371     /**
 372      * Returns an array containing the elements of this stream.
 373      *
 374      * <p>This is a <a href="package-summary.html#StreamOps">terminal
 375      * operation</a>.
 376      *
 377      * @return an array containing the elements of this stream
 378      */
 379     int[] toArray();
 380 
 381     /**
 382      * Performs a <a href="package-summary.html#Reduction">reduction</a> on the
 383      * elements of this stream, using the provided identity value and an
 384      * <a href="package-summary.html#Associativity">associative</a>
 385      * accumulation function, and returns the reduced value.  This is equivalent
 386      * to:
 387      * <pre>{@code
 388      *     int result = identity;
 389      *     for (int element : this stream)
 390      *         result = accumulator.apply(result, element)
 391      *     return result;
 392      * }</pre>
 393      *
 394      * but is not constrained to execute sequentially.
 395      *
 396      * <p>The {@code identity} value must be an identity for the accumulator
 397      * function. This means that for all {@code x},
 398      * {@code accumulator.apply(identity, x)} is equal to {@code x}.
 399      * The {@code accumulator} function must be an
 400      * <a href="package-summary.html#Associativity">associative</a> function.
 401      *
 402      * <p>This is a <a href="package-summary.html#StreamOps">terminal
 403      * operation</a>.
 404      *
 405      * @apiNote Sum, min, max, and average are all special cases of reduction.
 406      * Summing a stream of numbers can be expressed as:
 407      *
 408      * <pre>{@code
 409      *     int sum = integers.reduce(0, (a, b) -> a+b);
 410      * }</pre>
 411      *
 412      * or more compactly:
 413      *
 414      * <pre>{@code
 415      *     int sum = integers.reduce(0, Integer::sum);
 416      * }</pre>
 417      *
 418      * <p>While this may seem a more roundabout way to perform an aggregation
 419      * compared to simply mutating a running total in a loop, reduction
 420      * operations parallelize more gracefully, without needing additional
 421      * synchronization and with greatly reduced risk of data races.
 422      *
 423      * @param identity the identity value for the accumulating function
 424      * @param op an <a href="package-summary.html#Associativity">associative</a>
 425      *                    <a href="package-summary.html#NonInterference">non-interfering,
 426      *                    stateless</a> function for combining two values
 427      * @return the result of the reduction
 428      * @see #sum()
 429      * @see #min()
 430      * @see #max()
 431      * @see #average()
 432      */
 433     int reduce(int identity, IntBinaryOperator op);
 434 
 435     /**
 436      * Performs a <a href="package-summary.html#Reduction">reduction</a> on the
 437      * elements of this stream, using an
 438      * <a href="package-summary.html#Associativity">associative</a> accumulation
 439      * function, and returns an {@code OptionalInt} describing the reduced value,
 440      * if any. This is equivalent to:
 441      * <pre>{@code
 442      *     boolean foundAny = false;
 443      *     int result = null;
 444      *     for (int element : this stream) {
 445      *         if (!foundAny) {
 446      *             foundAny = true;
 447      *             result = element;
 448      *         }
 449      *         else
 450      *             result = accumulator.apply(result, element);
 451      *     }
 452      *     return foundAny ? OptionalInt.of(result) : OptionalInt.empty();
 453      * }</pre>
 454      *
 455      * but is not constrained to execute sequentially.
 456      *
 457      * <p>The {@code accumulator} function must be an
 458      * <a href="package-summary.html#Associativity">associative</a> function.
 459      *
 460      * <p>This is a <a href="package-summary.html#StreamOps">terminal
 461      * operation</a>.
 462      *
 463      * @param op an <a href="package-summary.html#Associativity">associative</a>
 464      *           <a href="package-summary.html#NonInterference">non-interfering,
 465      *           stateless</a> function for combining two values
 466      * @return the result of the reduction
 467      * @see #reduce(int, IntBinaryOperator)
 468      */
 469     OptionalInt reduce(IntBinaryOperator op);
 470 
 471     /**
 472      * Performs a <a href="package-summary.html#MutableReduction">mutable
 473      * reduction</a> operation on the elements of this stream.  A mutable
 474      * reduction is one in which the reduced value is a mutable result container,
 475      * such as an {@code ArrayList}, and elements are incorporated by updating
 476      * the state of the result rather than by replacing the result.  This
 477      * produces a result equivalent to:
 478      * <pre>{@code
 479      *     R result = supplier.get();
 480      *     for (int element : this stream)
 481      *         accumulator.accept(result, element);
 482      *     return result;
 483      * }</pre>
 484      *
 485      * <p>Like {@link #reduce(int, IntBinaryOperator)}, {@code collect} operations
 486      * can be parallelized without requiring additional synchronization.
 487      *
 488      * <p>This is a <a href="package-summary.html#StreamOps">terminal
 489      * operation</a>.
 490      *
 491      * @param <R> type of the result
 492      * @param supplier a function that creates a new result container. For a
 493      *                 parallel execution, this function may be called
 494      *                 multiple times and must return a fresh value each time.
 495      * @param accumulator an <a href="package-summary.html#Associativity">associative</a>
 496      *                    <a href="package-summary.html#NonInterference">non-interfering,
 497      *                    stateless</a> function for incorporating an additional
 498      *                    element into a result
 499      * @param combiner an <a href="package-summary.html#Associativity">associative</a>
 500      *                 <a href="package-summary.html#NonInterference">non-interfering,
 501      *                 stateless</a> function for combining two values, which
 502      *                 must be compatible with the accumulator function
 503      * @return the result of the reduction
 504      * @see Stream#collect(Supplier, BiConsumer, BiConsumer)
 505      */
 506     <R> R collect(Supplier<R> supplier,
 507                   ObjIntConsumer<R> accumulator,
 508                   BiConsumer<R, R> combiner);
 509 
 510     /**
 511      * Returns the sum of elements in this stream.  This is a special case
 512      * of a <a href="package-summary.html#Reduction">reduction</a>
 513      * and is equivalent to:
 514      * <pre>{@code
 515      *     return reduce(0, Integer::sum);
 516      * }</pre>
 517      *
 518      * <p>This is a <a href="package-summary.html#StreamOps">terminal
 519      * operation</a>.
 520      *
 521      * @return the sum of elements in this stream
 522      */
 523     int sum();
 524 
 525     /**
 526      * Returns an {@code OptionalInt} describing the minimum element of this
 527      * stream, or an empty optional if this stream is empty.  This is a special
 528      * case of a <a href="package-summary.html#Reduction">reduction</a>
 529      * and is equivalent to:
 530      * <pre>{@code
 531      *     return reduce(Integer::min);
 532      * }</pre>
 533      *
 534      * <p>This is a <a href="package-summary.html#StreamOps">terminal operation</a>.
 535      *
 536      * @return an {@code OptionalInt} containing the minimum element of this
 537      * stream, or an empty {@code OptionalInt} if the stream is empty
 538      */
 539     OptionalInt min();
 540 
 541     /**
 542      * Returns an {@code OptionalInt} describing the maximum element of this
 543      * stream, or an empty optional if this stream is empty.  This is a special
 544      * case of a <a href="package-summary.html#Reduction">reduction</a>
 545      * and is equivalent to:
 546      * <pre>{@code
 547      *     return reduce(Integer::max);
 548      * }</pre>
 549      *
 550      * <p>This is a <a href="package-summary.html#StreamOps">terminal
 551      * operation</a>.
 552      *
 553      * @return an {@code OptionalInt} containing the maximum element of this
 554      * stream, or an empty {@code OptionalInt} if the stream is empty
 555      */
 556     OptionalInt max();
 557 
 558     /**
 559      * Returns the count of elements in this stream.  This is a special case of
 560      * a <a href="package-summary.html#Reduction">reduction</a> and is
 561      * equivalent to:
 562      * <pre>{@code
 563      *     return mapToLong(e -> 1L).sum();
 564      * }</pre>
 565      *
 566      * <p>This is a <a href="package-summary.html#StreamOps">terminal operation</a>.
 567      *
 568      * @return the count of elements in this stream
 569      */
 570     long count();
 571 
 572     /**
 573      * Returns an {@code OptionalDouble} describing the arithmetic mean of elements of
 574      * this stream, or an empty optional if this stream is empty.  This is a
 575      * special case of a
 576      * <a href="package-summary.html#Reduction">reduction</a>.
 577      *
 578      * <p>This is a <a href="package-summary.html#StreamOps">terminal
 579      * operation</a>.
 580      *
 581      * @return an {@code OptionalDouble} containing the average element of this
 582      * stream, or an empty optional if the stream is empty
 583      */
 584     OptionalDouble average();
 585 
 586     /**
 587      * Returns an {@code IntSummaryStatistics} describing various
 588      * summary data about the elements of this stream.  This is a special
 589      * case of a <a href="package-summary.html#Reduction">reduction</a>.
 590      *
 591      * <p>This is a <a href="package-summary.html#StreamOps">terminal
 592      * operation</a>.
 593      *
 594      * @return an {@code IntSummaryStatistics} describing various summary data
 595      * about the elements of this stream
 596      */
 597     IntSummaryStatistics summaryStatistics();
 598 
 599     /**
 600      * Returns whether any elements of this stream match the provided
 601      * predicate.  May not evaluate the predicate on all elements if not
 602      * necessary for determining the result.
 603      *
 604      * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting
 605      * terminal operation</a>.
 606      *
 607      * @param predicate a <a href="package-summary.html#NonInterference">non-interfering,
 608      *                  stateless</a> predicate to apply to elements of this
 609      *                  stream
 610      * @return {@code true} if any elements of the stream match the provided
 611      * predicate otherwise {@code false}
 612      */
 613     boolean anyMatch(IntPredicate predicate);
 614 
 615     /**
 616      * Returns whether all elements of this stream match the provided predicate.
 617      * May not evaluate the predicate on all elements if not necessary for
 618      * determining the result.
 619      *
 620      * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting
 621      * terminal operation</a>.
 622      *
 623      * @param predicate a <a href="package-summary.html#NonInterference">non-interfering,
 624      *                  stateless</a> predicate to apply to elements of this
 625      *                  stream
 626      * @return {@code true} if all elements of the stream match the provided
 627      * predicate otherwise {@code false}
 628      */
 629     boolean allMatch(IntPredicate predicate);
 630 
 631     /**
 632      * Returns whether no elements of this stream match the provided predicate.
 633      * May not evaluate the predicate on all elements if not necessary for
 634      * determining the result.
 635      *
 636      * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting
 637      * terminal operation</a>.
 638      *
 639      * @param predicate a <a href="package-summary.html#NonInterference">non-interfering,
 640      *                  stateless</a> predicate to apply to elements of this
 641      *                  stream
 642      * @return {@code true} if no elements of the stream match the provided
 643      * predicate otherwise {@code false}
 644      */
 645     boolean noneMatch(IntPredicate predicate);
 646 
 647     /**
 648      * Returns an {@link OptionalInt} describing the first element of this
 649      * stream, or an empty {@code OptionalInt} if the stream is empty.  If the
 650      * stream has no encounter order, then any element may be returned.
 651      *
 652      * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting
 653      * terminal operation</a>.
 654      *
 655      * @return an {@code OptionalInt} describing the first element of this stream,
 656      * or an empty {@code OptionalInt} if the stream is empty
 657      */
 658     OptionalInt findFirst();
 659 
 660     /**
 661      * Returns an {@link OptionalInt} describing some element of the stream, or
 662      * an empty {@code OptionalInt} if the stream is empty.
 663      *
 664      * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting
 665      * terminal operation</a>.
 666      *
 667      * <p>The behavior of this operation is explicitly nondeterministic; it is
 668      * free to select any element in the stream.  This is to allow for maximal
 669      * performance in parallel operations; the cost is that multiple invocations
 670      * on the same source may not return the same result.  (If a stable result
 671      * is desired, use {@link #findFirst()} instead.)
 672      *
 673      * @return an {@code OptionalInt} describing some element of this stream, or
 674      * an empty {@code OptionalInt} if the stream is empty
 675      * @see #findFirst()
 676      */
 677     OptionalInt findAny();
 678 
 679     /**
 680      * Returns a {@code LongStream} consisting of the elements of this stream,
 681      * converted to {@code long}.
 682      *
 683      * <p>This is an <a href="package-summary.html#StreamOps">intermediate
 684      * operation</a>.
 685      *
 686      * @return a {@code LongStream} consisting of the elements of this stream,
 687      * converted to {@code long}
 688      */
 689     LongStream asLongStream();
 690 
 691     /**
 692      * Returns a {@code DoubleStream} consisting of the elements of this stream,
 693      * converted to {@code double}.
 694      *
 695      * <p>This is an <a href="package-summary.html#StreamOps">intermediate
 696      * operation</a>.
 697      *
 698      * @return a {@code DoubleStream} consisting of the elements of this stream,
 699      * converted to {@code double}
 700      */
 701     DoubleStream asDoubleStream();
 702 
 703     /**
 704      * Returns a {@code Stream} consisting of the elements of this stream,
 705      * each boxed to an {@code Integer}.
 706      *
 707      * <p>This is an <a href="package-summary.html#StreamOps">intermediate
 708      * operation</a>.
 709      *
 710      * @return a {@code Stream} consistent of the elements of this stream,
 711      * each boxed to an {@code Integer}
 712      */
 713     Stream<Integer> boxed();
 714 
 715     @Override
 716     IntStream sequential();
 717 
 718     @Override
 719     IntStream parallel();
 720 
 721     @Override
 722     PrimitiveIterator.OfInt iterator();
 723 
 724     @Override
 725     Spliterator.OfInt spliterator();
 726 
 727     // Static factories
 728 
 729     /**
 730      * Returns a builder for an {@code IntStream}.
 731      *
 732      * @return a stream builder
 733      */
 734     public static Builder builder() {
 735         return new Streams.IntStreamBuilderImpl();
 736     }
 737 
 738     /**
 739      * Returns an empty sequential {@code IntStream}.
 740      *
 741      * @return an empty sequential stream
 742      */
 743     public static IntStream empty() {
 744         return StreamSupport.intStream(Spliterators.emptyIntSpliterator(), false);
 745     }
 746 
 747     /**
 748      * Returns a sequential {@code IntStream} containing a single element.
 749      *
 750      * @param t the single element
 751      * @return a singleton sequential stream
 752      */
 753     public static IntStream of(int t) {
 754         return StreamSupport.intStream(new Streams.IntStreamBuilderImpl(t), false);
 755     }
 756 
 757     /**
 758      * Returns a sequential ordered stream whose elements are the specified values.
 759      *
 760      * @param values the elements of the new stream
 761      * @return the new stream
 762      */
 763     public static IntStream of(int... values) {
 764         return Arrays.stream(values);
 765     }
 766 
 767     /**
 768      * Returns an infinite sequential ordered {@code IntStream} produced by iterative
 769      * application of a function {@code f} to an initial element {@code seed},
 770      * producing a {@code Stream} consisting of {@code seed}, {@code f(seed)},
 771      * {@code f(f(seed))}, etc.
 772      *
 773      * <p>The first element (position {@code 0}) in the {@code IntStream} will be
 774      * the provided {@code seed}.  For {@code n > 0}, the element at position
 775      * {@code n}, will be the result of applying the function {@code f} to the
 776      * element at position {@code n - 1}.
 777      *
 778      * @param seed the initial element
 779      * @param f a function to be applied to to the previous element to produce
 780      *          a new element
 781      * @return A new sequential {@code IntStream}
 782      */
 783     public static IntStream iterate(final int seed, final IntUnaryOperator f) {
 784         Objects.requireNonNull(f);
 785         final PrimitiveIterator.OfInt iterator = new PrimitiveIterator.OfInt() {
 786             int t = seed;
 787 
 788             @Override
 789             public boolean hasNext() {
 790                 return true;
 791             }
 792 
 793             @Override
 794             public int nextInt() {
 795                 int v = t;
 796                 t = f.applyAsInt(t);
 797                 return v;
 798             }
 799         };
 800         return StreamSupport.intStream(Spliterators.spliteratorUnknownSize(
 801                 iterator,
 802                 Spliterator.ORDERED | Spliterator.IMMUTABLE | Spliterator.NONNULL), false);
 803     }
 804 
 805     /**
 806      * Returns a sequential stream where each element is generated by
 807      * the provided {@code IntSupplier}.  This is suitable for generating
 808      * constant streams, streams of random elements, etc.
 809      *
 810      * @param s the {@code IntSupplier} for generated elements
 811      * @return a new sequential {@code IntStream}
 812      */
 813     public static IntStream generate(IntSupplier s) {
 814         Objects.requireNonNull(s);
 815         return StreamSupport.intStream(
 816                 new StreamSpliterators.InfiniteSupplyingSpliterator.OfInt(Long.MAX_VALUE, s), false);
 817     }
 818 
 819     /**
 820      * Returns a sequential ordered {@code IntStream} from {@code startInclusive}
 821      * (inclusive) to {@code endExclusive} (exclusive) by an incremental step of
 822      * {@code 1}.
 823      *
 824      * @apiNote
 825      * <p>An equivalent sequence of increasing values can be produced
 826      * sequentially using a {@code for} loop as follows:
 827      * <pre>{@code
 828      *     for (int i = startInclusive; i < endExclusive ; i++) { ... }
 829      * }</pre>
 830      *
 831      * @param startInclusive the (inclusive) initial value
 832      * @param endExclusive the exclusive upper bound
 833      * @return a sequential {@code IntStream} for the range of {@code int}
 834      *         elements
 835      */
 836     public static IntStream range(int startInclusive, int endExclusive) {
 837         if (startInclusive >= endExclusive) {
 838             return empty();
 839         } else {
 840             return StreamSupport.intStream(
 841                     new Streams.RangeIntSpliterator(startInclusive, endExclusive, false), false);
 842         }
 843     }
 844 
 845     /**
 846      * Returns a sequential ordered {@code IntStream} from {@code startInclusive}
 847      * (inclusive) to {@code endInclusive} (inclusive) by an incremental step of
 848      * {@code 1}.
 849      *
 850      * @apiNote
 851      * <p>An equivalent sequence of increasing values can be produced
 852      * sequentially using a {@code for} loop as follows:
 853      * <pre>{@code
 854      *     for (int i = startInclusive; i <= endInclusive ; i++) { ... }
 855      * }</pre>
 856      *
 857      * @param startInclusive the (inclusive) initial value
 858      * @param endInclusive the inclusive upper bound
 859      * @return a sequential {@code IntStream} for the range of {@code int}
 860      *         elements
 861      */
 862     public static IntStream rangeClosed(int startInclusive, int endInclusive) {
 863         if (startInclusive > endInclusive) {
 864             return empty();
 865         } else {
 866             return StreamSupport.intStream(
 867                     new Streams.RangeIntSpliterator(startInclusive, endInclusive, true), false);
 868         }
 869     }
 870 
 871     /**
 872      * Creates a lazily concatenated stream whose elements are all the
 873      * elements of the first stream followed by all the elements of the
 874      * second stream. The resulting stream is ordered if both
 875      * of the input streams are ordered, and parallel if either of the input
 876      * streams is parallel.  When the resulting stream is closed, the close
 877      * handlers for both input streams are invoked.
 878      *
 879      * @param a the first stream
 880      * @param b the second stream
 881      * @return the concatenation of the two input streams
 882      */
 883     public static IntStream concat(IntStream a, IntStream b) {
 884         Objects.requireNonNull(a);
 885         Objects.requireNonNull(b);
 886 
 887         Spliterator.OfInt split = new Streams.ConcatSpliterator.OfInt(
 888                 a.spliterator(), b.spliterator());
 889         IntStream stream = StreamSupport.intStream(split, a.isParallel() || b.isParallel());
 890         return stream.onClose(Streams.composedClose(a, b));
 891     }
 892 
 893     /**
 894      * A mutable builder for an {@code IntStream}.
 895      *
 896      * <p>A stream builder has a lifecycle, which starts in a building
 897      * phase, during which elements can be added, and then transitions to a built
 898      * phase, after which elements may not be added.  The built phase
 899      * begins when the {@link #build()} method is called, which creates an
 900      * ordered stream whose elements are the elements that were added to the
 901      * stream builder, in the order they were added.
 902      *
 903      * @see IntStream#builder()
 904      * @since 1.8
 905      */
 906     public interface Builder extends IntConsumer {
 907 
 908         /**
 909          * Adds an element to the stream being built.
 910          *
 911          * @throws IllegalStateException if the builder has already transitioned
 912          * to the built state
 913          */
 914         @Override
 915         void accept(int t);
 916 
 917         /**
 918          * Adds an element to the stream being built.
 919          *
 920          * @implSpec
 921          * The default implementation behaves as if:
 922          * <pre>{@code
 923          *     accept(t)
 924          *     return this;
 925          * }</pre>
 926          *
 927          * @param t the element to add
 928          * @return {@code this} builder
 929          * @throws IllegalStateException if the builder has already transitioned
 930          * to the built state
 931          */
 932         default Builder add(int t) {
 933             accept(t);
 934             return this;
 935         }
 936 
 937         /**
 938          * Builds the stream, transitioning this builder to the built state.
 939          * An {@code IllegalStateException} is thrown if there are further
 940          * attempts to operate on the builder after it has entered the built
 941          * state.
 942          *
 943          * @return the built stream
 944          * @throws IllegalStateException if the builder has already transitioned to
 945          * the built state
 946          */
 947         IntStream build();
 948     }
 949 }