1/*
2 * Copyright (c) 2012, 2016, 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 */
25package java.util.stream;
26
27import java.util.Arrays;
28import java.util.IntSummaryStatistics;
29import java.util.Objects;
30import java.util.OptionalDouble;
31import java.util.OptionalInt;
32import java.util.PrimitiveIterator;
33import java.util.Spliterator;
34import java.util.Spliterators;
35import java.util.function.BiConsumer;
36import java.util.function.Function;
37import java.util.function.IntBinaryOperator;
38import java.util.function.IntConsumer;
39import java.util.function.IntFunction;
40import java.util.function.IntPredicate;
41import java.util.function.IntSupplier;
42import java.util.function.IntToDoubleFunction;
43import java.util.function.IntToLongFunction;
44import java.util.function.IntUnaryOperator;
45import java.util.function.ObjIntConsumer;
46import java.util.function.Supplier;
47
48/**
49 * A sequence of primitive int-valued elements supporting sequential and parallel
50 * aggregate operations.  This is the {@code int} primitive specialization of
51 * {@link Stream}.
52 *
53 * <p>The following example illustrates an aggregate operation using
54 * {@link Stream} and {@link IntStream}, computing the sum of the weights of the
55 * red widgets:
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 * See the class documentation for {@link Stream} and the package documentation
65 * for <a href="package-summary.html">java.util.stream</a> for additional
66 * specification of streams, stream operations, stream pipelines, and
67 * parallelism.
68 *
69 * @since 1.8
70 * @see Stream
71 * @see <a href="package-summary.html">java.util.stream</a>
72 */
73public interface IntStream extends BaseStream<Integer, IntStream> {
74
75    /**
76     * Returns a stream consisting of the elements of this stream that match
77     * the given predicate.
78     *
79     * <p>This is an <a href="package-summary.html#StreamOps">intermediate
80     * operation</a>.
81     *
82     * @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>,
83     *                  <a href="package-summary.html#Statelessness">stateless</a>
84     *                  predicate to apply to each element to determine if it
85     *                  should be included
86     * @return the new stream
87     */
88    IntStream filter(IntPredicate predicate);
89
90    /**
91     * Returns a stream consisting of the results of applying the given
92     * function to the elements of this stream.
93     *
94     * <p>This is an <a href="package-summary.html#StreamOps">intermediate
95     * operation</a>.
96     *
97     * @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>,
98     *               <a href="package-summary.html#Statelessness">stateless</a>
99     *               function to apply to each element
100     * @return the new stream
101     */
102    IntStream map(IntUnaryOperator mapper);
103
104    /**
105     * Returns an object-valued {@code Stream} consisting of the results of
106     * applying the given function to the elements of this stream.
107     *
108     * <p>This is an <a href="package-summary.html#StreamOps">
109     *     intermediate operation</a>.
110     *
111     * @param <U> the element type of the new stream
112     * @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>,
113     *               <a href="package-summary.html#Statelessness">stateless</a>
114     *               function to apply to each element
115     * @return the new stream
116     */
117    <U> Stream<U> mapToObj(IntFunction<? extends U> mapper);
118
119    /**
120     * Returns a {@code LongStream} consisting of the results of applying the
121     * given function to the elements of this stream.
122     *
123     * <p>This is an <a href="package-summary.html#StreamOps">intermediate
124     * operation</a>.
125     *
126     * @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>,
127     *               <a href="package-summary.html#Statelessness">stateless</a>
128     *               function to apply to each element
129     * @return the new stream
130     */
131    LongStream mapToLong(IntToLongFunction mapper);
132
133    /**
134     * Returns a {@code DoubleStream} consisting of the results of applying the
135     * given function to the elements of this stream.
136     *
137     * <p>This is an <a href="package-summary.html#StreamOps">intermediate
138     * operation</a>.
139     *
140     * @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>,
141     *               <a href="package-summary.html#Statelessness">stateless</a>
142     *               function to apply to each element
143     * @return the new stream
144     */
145    DoubleStream mapToDouble(IntToDoubleFunction mapper);
146
147    /**
148     * Returns a stream consisting of the results of replacing each element of
149     * this stream with the contents of a mapped stream produced by applying
150     * the provided mapping function to each element.  Each mapped stream is
151     * {@link java.util.stream.BaseStream#close() closed} after its contents
152     * have been placed into this stream.  (If a mapped stream is {@code null}
153     * an empty stream is used, instead.)
154     *
155     * <p>This is an <a href="package-summary.html#StreamOps">intermediate
156     * operation</a>.
157     *
158     * @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>,
159     *               <a href="package-summary.html#Statelessness">stateless</a>
160     *               function to apply to each element which produces an
161     *               {@code IntStream} of new values
162     * @return the new stream
163     * @see Stream#flatMap(Function)
164     */
165    IntStream flatMap(IntFunction<? extends IntStream> mapper);
166
167    /**
168     * Returns a stream consisting of the distinct elements of this stream.
169     *
170     * <p>This is a <a href="package-summary.html#StreamOps">stateful
171     * intermediate operation</a>.
172     *
173     * @return the new stream
174     */
175    IntStream distinct();
176
177    /**
178     * Returns a stream consisting of the elements of this stream in sorted
179     * order.
180     *
181     * <p>This is a <a href="package-summary.html#StreamOps">stateful
182     * intermediate operation</a>.
183     *
184     * @return the new stream
185     */
186    IntStream sorted();
187
188    /**
189     * Returns a stream consisting of the elements of this stream, additionally
190     * performing the provided action on each element as elements are consumed
191     * from the resulting stream.
192     *
193     * <p>This is an <a href="package-summary.html#StreamOps">intermediate
194     * operation</a>.
195     *
196     * <p>For parallel stream pipelines, the action may be called at
197     * whatever time and in whatever thread the element is made available by the
198     * upstream operation.  If the action modifies shared state,
199     * it is responsible for providing the required synchronization.
200     *
201     * @apiNote This method exists mainly to support debugging, where you want
202     * to see the elements as they flow past a certain point in a pipeline:
203     * <pre>{@code
204     *     IntStream.of(1, 2, 3, 4)
205     *         .filter(e -> e > 2)
206     *         .peek(e -> System.out.println("Filtered value: " + e))
207     *         .map(e -> e * e)
208     *         .peek(e -> System.out.println("Mapped value: " + e))
209     *         .sum();
210     * }</pre>
211     *
212     * <p>In cases where the stream implementation is able to optimize away the
213     * production of some or all the elements (such as with short-circuiting
214     * operations like {@code findFirst}, or in the example described in
215     * {@link #count}), the action will not be invoked for those elements.
216     *
217     * @param action a <a href="package-summary.html#NonInterference">
218     *               non-interfering</a> action to perform on the elements as
219     *               they are consumed from the stream
220     * @return the new stream
221     */
222    IntStream peek(IntConsumer action);
223
224    /**
225     * Returns a stream consisting of the elements of this stream, truncated
226     * to be no longer than {@code maxSize} in length.
227     *
228     * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting
229     * stateful intermediate operation</a>.
230     *
231     * @apiNote
232     * While {@code limit()} is generally a cheap operation on sequential
233     * stream pipelines, it can be quite expensive on ordered parallel pipelines,
234     * especially for large values of {@code maxSize}, since {@code limit(n)}
235     * is constrained to return not just any <em>n</em> elements, but the
236     * <em>first n</em> elements in the encounter order.  Using an unordered
237     * stream source (such as {@link #generate(IntSupplier)}) or removing the
238     * ordering constraint with {@link #unordered()} may result in significant
239     * speedups of {@code limit()} in parallel pipelines, if the semantics of
240     * your situation permit.  If consistency with encounter order is required,
241     * and you are experiencing poor performance or memory utilization with
242     * {@code limit()} in parallel pipelines, switching to sequential execution
243     * with {@link #sequential()} may improve performance.
244     *
245     * @param maxSize the number of elements the stream should be limited to
246     * @return the new stream
247     * @throws IllegalArgumentException if {@code maxSize} is negative
248     */
249    IntStream limit(long maxSize);
250
251    /**
252     * Returns a stream consisting of the remaining elements of this stream
253     * after discarding the first {@code n} elements of the stream.
254     * If this stream contains fewer than {@code n} elements then an
255     * empty stream will be returned.
256     *
257     * <p>This is a <a href="package-summary.html#StreamOps">stateful
258     * intermediate operation</a>.
259     *
260     * @apiNote
261     * While {@code skip()} is generally a cheap operation on sequential
262     * stream pipelines, it can be quite expensive on ordered parallel pipelines,
263     * especially for large values of {@code n}, since {@code skip(n)}
264     * is constrained to skip not just any <em>n</em> elements, but the
265     * <em>first n</em> elements in the encounter order.  Using an unordered
266     * stream source (such as {@link #generate(IntSupplier)}) or removing the
267     * ordering constraint with {@link #unordered()} may result in significant
268     * speedups of {@code skip()} in parallel pipelines, if the semantics of
269     * your situation permit.  If consistency with encounter order is required,
270     * and you are experiencing poor performance or memory utilization with
271     * {@code skip()} in parallel pipelines, switching to sequential execution
272     * with {@link #sequential()} may improve performance.
273     *
274     * @param n the number of leading elements to skip
275     * @return the new stream
276     * @throws IllegalArgumentException if {@code n} is negative
277     */
278    IntStream skip(long n);
279
280    /**
281     * Returns, if this stream is ordered, a stream consisting of the longest
282     * prefix of elements taken from this stream that match the given predicate.
283     * Otherwise returns, if this stream is unordered, a stream consisting of a
284     * subset of elements taken from this stream that match the given predicate.
285     *
286     * <p>If this stream is ordered then the longest prefix is a contiguous
287     * sequence of elements of this stream that match the given predicate.  The
288     * first element of the sequence is the first element of this stream, and
289     * the element immediately following the last element of the sequence does
290     * not match the given predicate.
291     *
292     * <p>If this stream is unordered, and some (but not all) elements of this
293     * stream match the given predicate, then the behavior of this operation is
294     * nondeterministic; it is free to take any subset of matching elements
295     * (which includes the empty set).
296     *
297     * <p>Independent of whether this stream is ordered or unordered if all
298     * elements of this stream match the given predicate then this operation
299     * takes all elements (the result is the same as the input), or if no
300     * elements of the stream match the given predicate then no elements are
301     * taken (the result is an empty stream).
302     *
303     * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting
304     * stateful intermediate operation</a>.
305     *
306     * @implSpec
307     * The default implementation obtains the {@link #spliterator() spliterator}
308     * of this stream, wraps that spliterator so as to support the semantics
309     * of this operation on traversal, and returns a new stream associated with
310     * the wrapped spliterator.  The returned stream preserves the execution
311     * characteristics of this stream (namely parallel or sequential execution
312     * as per {@link #isParallel()}) but the wrapped spliterator may choose to
313     * not support splitting.  When the returned stream is closed, the close
314     * handlers for both the returned and this stream are invoked.
315     *
316     * @apiNote
317     * While {@code takeWhile()} is generally a cheap operation on sequential
318     * stream pipelines, it can be quite expensive on ordered parallel
319     * pipelines, since the operation is constrained to return not just any
320     * valid prefix, but the longest prefix of elements in the encounter order.
321     * Using an unordered stream source (such as {@link #generate(IntSupplier)})
322     * or removing the ordering constraint with {@link #unordered()} may result
323     * in significant speedups of {@code takeWhile()} in parallel pipelines, if
324     * the semantics of your situation permit.  If consistency with encounter
325     * order is required, and you are experiencing poor performance or memory
326     * utilization with {@code takeWhile()} in parallel pipelines, switching to
327     * sequential execution with {@link #sequential()} may improve performance.
328     *
329     * @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>,
330     *                  <a href="package-summary.html#Statelessness">stateless</a>
331     *                  predicate to apply to elements to determine the longest
332     *                  prefix of elements.
333     * @return the new stream
334     * @since 9
335     */
336    default IntStream takeWhile(IntPredicate predicate) {
337        Objects.requireNonNull(predicate);
338        // Reuses the unordered spliterator, which, when encounter is present,
339        // is safe to use as long as it configured not to split
340        return StreamSupport.intStream(
341                new WhileOps.UnorderedWhileSpliterator.OfInt.Taking(spliterator(), true, predicate),
342                isParallel()).onClose(this::close);
343    }
344
345    /**
346     * Returns, if this stream is ordered, a stream consisting of the remaining
347     * elements of this stream after dropping the longest prefix of elements
348     * that match the given predicate.  Otherwise returns, if this stream is
349     * unordered, a stream consisting of the remaining elements of this stream
350     * after dropping a subset of elements that match the given predicate.
351     *
352     * <p>If this stream is ordered then the longest prefix is a contiguous
353     * sequence of elements of this stream that match the given predicate.  The
354     * first element of the sequence is the first element of this stream, and
355     * the element immediately following the last element of the sequence does
356     * not match the given predicate.
357     *
358     * <p>If this stream is unordered, and some (but not all) elements of this
359     * stream match the given predicate, then the behavior of this operation is
360     * nondeterministic; it is free to drop any subset of matching elements
361     * (which includes the empty set).
362     *
363     * <p>Independent of whether this stream is ordered or unordered if all
364     * elements of this stream match the given predicate then this operation
365     * drops all elements (the result is an empty stream), or if no elements of
366     * the stream match the given predicate then no elements are dropped (the
367     * result is the same as the input).
368     *
369     * <p>This is a <a href="package-summary.html#StreamOps">stateful
370     * intermediate operation</a>.
371     *
372     * @implSpec
373     * The default implementation obtains the {@link #spliterator() spliterator}
374     * of this stream, wraps that spliterator so as to support the semantics
375     * of this operation on traversal, and returns a new stream associated with
376     * the wrapped spliterator.  The returned stream preserves the execution
377     * characteristics of this stream (namely parallel or sequential execution
378     * as per {@link #isParallel()}) but the wrapped spliterator may choose to
379     * not support splitting.  When the returned stream is closed, the close
380     * handlers for both the returned and this stream are invoked.
381     *
382     * @apiNote
383     * While {@code dropWhile()} is generally a cheap operation on sequential
384     * stream pipelines, it can be quite expensive on ordered parallel
385     * pipelines, since the operation is constrained to return not just any
386     * valid prefix, but the longest prefix of elements in the encounter order.
387     * Using an unordered stream source (such as {@link #generate(IntSupplier)})
388     * or removing the ordering constraint with {@link #unordered()} may result
389     * in significant speedups of {@code dropWhile()} in parallel pipelines, if
390     * the semantics of your situation permit.  If consistency with encounter
391     * order is required, and you are experiencing poor performance or memory
392     * utilization with {@code dropWhile()} in parallel pipelines, switching to
393     * sequential execution with {@link #sequential()} may improve performance.
394     *
395     * @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>,
396     *                  <a href="package-summary.html#Statelessness">stateless</a>
397     *                  predicate to apply to elements to determine the longest
398     *                  prefix of elements.
399     * @return the new stream
400     * @since 9
401     */
402    default IntStream dropWhile(IntPredicate predicate) {
403        Objects.requireNonNull(predicate);
404        // Reuses the unordered spliterator, which, when encounter is present,
405        // is safe to use as long as it configured not to split
406        return StreamSupport.intStream(
407                new WhileOps.UnorderedWhileSpliterator.OfInt.Dropping(spliterator(), true, predicate),
408                isParallel()).onClose(this::close);
409    }
410
411    /**
412     * Performs an action for each element of this stream.
413     *
414     * <p>This is a <a href="package-summary.html#StreamOps">terminal
415     * operation</a>.
416     *
417     * <p>For parallel stream pipelines, this operation does <em>not</em>
418     * guarantee to respect the encounter order of the stream, as doing so
419     * would sacrifice the benefit of parallelism.  For any given element, the
420     * action may be performed at whatever time and in whatever thread the
421     * library chooses.  If the action accesses shared state, it is
422     * responsible for providing the required synchronization.
423     *
424     * @param action a <a href="package-summary.html#NonInterference">
425     *               non-interfering</a> action to perform on the elements
426     */
427    void forEach(IntConsumer action);
428
429    /**
430     * Performs an action for each element of this stream, guaranteeing that
431     * each element is processed in encounter order for streams that have a
432     * defined encounter order.
433     *
434     * <p>This is a <a href="package-summary.html#StreamOps">terminal
435     * operation</a>.
436     *
437     * @param action a <a href="package-summary.html#NonInterference">
438     *               non-interfering</a> action to perform on the elements
439     * @see #forEach(IntConsumer)
440     */
441    void forEachOrdered(IntConsumer action);
442
443    /**
444     * Returns an array containing the elements of this stream.
445     *
446     * <p>This is a <a href="package-summary.html#StreamOps">terminal
447     * operation</a>.
448     *
449     * @return an array containing the elements of this stream
450     */
451    int[] toArray();
452
453    /**
454     * Performs a <a href="package-summary.html#Reduction">reduction</a> on the
455     * elements of this stream, using the provided identity value and an
456     * <a href="package-summary.html#Associativity">associative</a>
457     * accumulation function, and returns the reduced value.  This is equivalent
458     * to:
459     * <pre>{@code
460     *     int result = identity;
461     *     for (int element : this stream)
462     *         result = accumulator.applyAsInt(result, element)
463     *     return result;
464     * }</pre>
465     *
466     * but is not constrained to execute sequentially.
467     *
468     * <p>The {@code identity} value must be an identity for the accumulator
469     * function. This means that for all {@code x},
470     * {@code accumulator.apply(identity, x)} is equal to {@code x}.
471     * The {@code accumulator} function must be an
472     * <a href="package-summary.html#Associativity">associative</a> function.
473     *
474     * <p>This is a <a href="package-summary.html#StreamOps">terminal
475     * operation</a>.
476     *
477     * @apiNote Sum, min, max, and average are all special cases of reduction.
478     * Summing a stream of numbers can be expressed as:
479     *
480     * <pre>{@code
481     *     int sum = integers.reduce(0, (a, b) -> a+b);
482     * }</pre>
483     *
484     * or more compactly:
485     *
486     * <pre>{@code
487     *     int sum = integers.reduce(0, Integer::sum);
488     * }</pre>
489     *
490     * <p>While this may seem a more roundabout way to perform an aggregation
491     * compared to simply mutating a running total in a loop, reduction
492     * operations parallelize more gracefully, without needing additional
493     * synchronization and with greatly reduced risk of data races.
494     *
495     * @param identity the identity value for the accumulating function
496     * @param op an <a href="package-summary.html#Associativity">associative</a>,
497     *           <a href="package-summary.html#NonInterference">non-interfering</a>,
498     *           <a href="package-summary.html#Statelessness">stateless</a>
499     *           function for combining two values
500     * @return the result of the reduction
501     * @see #sum()
502     * @see #min()
503     * @see #max()
504     * @see #average()
505     */
506    int reduce(int identity, IntBinaryOperator op);
507
508    /**
509     * Performs a <a href="package-summary.html#Reduction">reduction</a> on the
510     * elements of this stream, using an
511     * <a href="package-summary.html#Associativity">associative</a> accumulation
512     * function, and returns an {@code OptionalInt} describing the reduced value,
513     * if any. This is equivalent to:
514     * <pre>{@code
515     *     boolean foundAny = false;
516     *     int result = null;
517     *     for (int element : this stream) {
518     *         if (!foundAny) {
519     *             foundAny = true;
520     *             result = element;
521     *         }
522     *         else
523     *             result = accumulator.applyAsInt(result, element);
524     *     }
525     *     return foundAny ? OptionalInt.of(result) : OptionalInt.empty();
526     * }</pre>
527     *
528     * but is not constrained to execute sequentially.
529     *
530     * <p>The {@code accumulator} function must be an
531     * <a href="package-summary.html#Associativity">associative</a> function.
532     *
533     * <p>This is a <a href="package-summary.html#StreamOps">terminal
534     * operation</a>.
535     *
536     * @param op an <a href="package-summary.html#Associativity">associative</a>,
537     *           <a href="package-summary.html#NonInterference">non-interfering</a>,
538     *           <a href="package-summary.html#Statelessness">stateless</a>
539     *           function for combining two values
540     * @return the result of the reduction
541     * @see #reduce(int, IntBinaryOperator)
542     */
543    OptionalInt reduce(IntBinaryOperator op);
544
545    /**
546     * Performs a <a href="package-summary.html#MutableReduction">mutable
547     * reduction</a> operation on the elements of this stream.  A mutable
548     * reduction is one in which the reduced value is a mutable result container,
549     * such as an {@code ArrayList}, and elements are incorporated by updating
550     * the state of the result rather than by replacing the result.  This
551     * produces a result equivalent to:
552     * <pre>{@code
553     *     R result = supplier.get();
554     *     for (int element : this stream)
555     *         accumulator.accept(result, element);
556     *     return result;
557     * }</pre>
558     *
559     * <p>Like {@link #reduce(int, IntBinaryOperator)}, {@code collect} operations
560     * can be parallelized without requiring additional synchronization.
561     *
562     * <p>This is a <a href="package-summary.html#StreamOps">terminal
563     * operation</a>.
564     *
565     * @param <R> the type of the mutable result container
566     * @param supplier a function that creates a new mutable result container.
567     *                 For a parallel execution, this function may be called
568     *                 multiple times and must return a fresh value each time.
569     * @param accumulator an <a href="package-summary.html#Associativity">associative</a>,
570     *                    <a href="package-summary.html#NonInterference">non-interfering</a>,
571     *                    <a href="package-summary.html#Statelessness">stateless</a>
572     *                    function that must fold an element into a result
573     *                    container.
574     * @param combiner an <a href="package-summary.html#Associativity">associative</a>,
575     *                    <a href="package-summary.html#NonInterference">non-interfering</a>,
576     *                    <a href="package-summary.html#Statelessness">stateless</a>
577     *                    function that accepts two partial result containers
578     *                    and merges them, which must be compatible with the
579     *                    accumulator function.  The combiner function must fold
580     *                    the elements from the second result container into the
581     *                    first result container.
582     * @return the result of the reduction
583     * @see Stream#collect(Supplier, BiConsumer, BiConsumer)
584     */
585    <R> R collect(Supplier<R> supplier,
586                  ObjIntConsumer<R> accumulator,
587                  BiConsumer<R, R> combiner);
588
589    /**
590     * Returns the sum of elements in this stream.  This is a special case
591     * of a <a href="package-summary.html#Reduction">reduction</a>
592     * and is equivalent to:
593     * <pre>{@code
594     *     return reduce(0, Integer::sum);
595     * }</pre>
596     *
597     * <p>This is a <a href="package-summary.html#StreamOps">terminal
598     * operation</a>.
599     *
600     * @return the sum of elements in this stream
601     */
602    int sum();
603
604    /**
605     * Returns an {@code OptionalInt} describing the minimum element of this
606     * stream, or an empty optional if this stream is empty.  This is a special
607     * case of a <a href="package-summary.html#Reduction">reduction</a>
608     * and is equivalent to:
609     * <pre>{@code
610     *     return reduce(Integer::min);
611     * }</pre>
612     *
613     * <p>This is a <a href="package-summary.html#StreamOps">terminal operation</a>.
614     *
615     * @return an {@code OptionalInt} containing the minimum element of this
616     * stream, or an empty {@code OptionalInt} if the stream is empty
617     */
618    OptionalInt min();
619
620    /**
621     * Returns an {@code OptionalInt} describing the maximum element of this
622     * stream, or an empty optional if this stream is empty.  This is a special
623     * case of a <a href="package-summary.html#Reduction">reduction</a>
624     * and is equivalent to:
625     * <pre>{@code
626     *     return reduce(Integer::max);
627     * }</pre>
628     *
629     * <p>This is a <a href="package-summary.html#StreamOps">terminal
630     * operation</a>.
631     *
632     * @return an {@code OptionalInt} containing the maximum element of this
633     * stream, or an empty {@code OptionalInt} if the stream is empty
634     */
635    OptionalInt max();
636
637    /**
638     * Returns the count of elements in this stream.  This is a special case of
639     * a <a href="package-summary.html#Reduction">reduction</a> and is
640     * equivalent to:
641     * <pre>{@code
642     *     return mapToLong(e -> 1L).sum();
643     * }</pre>
644     *
645     * <p>This is a <a href="package-summary.html#StreamOps">terminal operation</a>.
646     *
647     * @apiNote
648     * An implementation may choose to not execute the stream pipeline (either
649     * sequentially or in parallel) if it is capable of computing the count
650     * directly from the stream source.  In such cases no source elements will
651     * be traversed and no intermediate operations will be evaluated.
652     * Behavioral parameters with side-effects, which are strongly discouraged
653     * except for harmless cases such as debugging, may be affected.  For
654     * example, consider the following stream:
655     * <pre>{@code
656     *     IntStream s = IntStream.of(1, 2, 3, 4);
657     *     long count = s.peek(System.out::println).count();
658     * }</pre>
659     * The number of elements covered by the stream source is known and the
660     * intermediate operation, {@code peek}, does not inject into or remove
661     * elements from the stream (as may be the case for {@code flatMap} or
662     * {@code filter} operations).  Thus the count is 4 and there is no need to
663     * execute the pipeline and, as a side-effect, print out the elements.
664     *
665     * @return the count of elements in this stream
666     */
667    long count();
668
669    /**
670     * Returns an {@code OptionalDouble} describing the arithmetic mean of elements of
671     * this stream, or an empty optional if this stream is empty.  This is a
672     * special case of a
673     * <a href="package-summary.html#Reduction">reduction</a>.
674     *
675     * <p>This is a <a href="package-summary.html#StreamOps">terminal
676     * operation</a>.
677     *
678     * @return an {@code OptionalDouble} containing the average element of this
679     * stream, or an empty optional if the stream is empty
680     */
681    OptionalDouble average();
682
683    /**
684     * Returns an {@code IntSummaryStatistics} describing various
685     * summary data about the elements of this stream.  This is a special
686     * case of a <a href="package-summary.html#Reduction">reduction</a>.
687     *
688     * <p>This is a <a href="package-summary.html#StreamOps">terminal
689     * operation</a>.
690     *
691     * @return an {@code IntSummaryStatistics} describing various summary data
692     * about the elements of this stream
693     */
694    IntSummaryStatistics summaryStatistics();
695
696    /**
697     * Returns whether any elements of this stream match the provided
698     * predicate.  May not evaluate the predicate on all elements if not
699     * necessary for determining the result.  If the stream is empty then
700     * {@code false} is returned and the predicate is not evaluated.
701     *
702     * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting
703     * terminal operation</a>.
704     *
705     * @apiNote
706     * This method evaluates the <em>existential quantification</em> of the
707     * predicate over the elements of the stream (for some x P(x)).
708     *
709     * @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>,
710     *                  <a href="package-summary.html#Statelessness">stateless</a>
711     *                  predicate to apply to elements of this stream
712     * @return {@code true} if any elements of the stream match the provided
713     * predicate, otherwise {@code false}
714     */
715    boolean anyMatch(IntPredicate predicate);
716
717    /**
718     * Returns whether all elements of this stream match the provided predicate.
719     * May not evaluate the predicate on all elements if not necessary for
720     * determining the result.  If the stream is empty then {@code true} is
721     * returned and the predicate is not evaluated.
722     *
723     * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting
724     * terminal operation</a>.
725     *
726     * @apiNote
727     * This method evaluates the <em>universal quantification</em> of the
728     * predicate over the elements of the stream (for all x P(x)).  If the
729     * stream is empty, the quantification is said to be <em>vacuously
730     * satisfied</em> and is always {@code true} (regardless of P(x)).
731     *
732     * @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>,
733     *                  <a href="package-summary.html#Statelessness">stateless</a>
734     *                  predicate to apply to elements of this stream
735     * @return {@code true} if either all elements of the stream match the
736     * provided predicate or the stream is empty, otherwise {@code false}
737     */
738    boolean allMatch(IntPredicate predicate);
739
740    /**
741     * Returns whether no elements of this stream match the provided predicate.
742     * May not evaluate the predicate on all elements if not necessary for
743     * determining the result.  If the stream is empty then {@code true} is
744     * returned and the predicate is not evaluated.
745     *
746     * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting
747     * terminal operation</a>.
748     *
749     * @apiNote
750     * This method evaluates the <em>universal quantification</em> of the
751     * negated predicate over the elements of the stream (for all x ~P(x)).  If
752     * the stream is empty, the quantification is said to be vacuously satisfied
753     * and is always {@code true}, regardless of P(x).
754     *
755     * @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>,
756     *                  <a href="package-summary.html#Statelessness">stateless</a>
757     *                  predicate to apply to elements of this stream
758     * @return {@code true} if either no elements of the stream match the
759     * provided predicate or the stream is empty, otherwise {@code false}
760     */
761    boolean noneMatch(IntPredicate predicate);
762
763    /**
764     * Returns an {@link OptionalInt} describing the first element of this
765     * stream, or an empty {@code OptionalInt} if the stream is empty.  If the
766     * stream has no encounter order, then any element may be returned.
767     *
768     * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting
769     * terminal operation</a>.
770     *
771     * @return an {@code OptionalInt} describing the first element of this stream,
772     * or an empty {@code OptionalInt} if the stream is empty
773     */
774    OptionalInt findFirst();
775
776    /**
777     * Returns an {@link OptionalInt} describing some element of the stream, or
778     * an empty {@code OptionalInt} if the stream is empty.
779     *
780     * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting
781     * terminal operation</a>.
782     *
783     * <p>The behavior of this operation is explicitly nondeterministic; it is
784     * free to select any element in the stream.  This is to allow for maximal
785     * performance in parallel operations; the cost is that multiple invocations
786     * on the same source may not return the same result.  (If a stable result
787     * is desired, use {@link #findFirst()} instead.)
788     *
789     * @return an {@code OptionalInt} describing some element of this stream, or
790     * an empty {@code OptionalInt} if the stream is empty
791     * @see #findFirst()
792     */
793    OptionalInt findAny();
794
795    /**
796     * Returns a {@code LongStream} consisting of the elements of this stream,
797     * converted to {@code long}.
798     *
799     * <p>This is an <a href="package-summary.html#StreamOps">intermediate
800     * operation</a>.
801     *
802     * @return a {@code LongStream} consisting of the elements of this stream,
803     * converted to {@code long}
804     */
805    LongStream asLongStream();
806
807    /**
808     * Returns a {@code DoubleStream} consisting of the elements of this stream,
809     * converted to {@code double}.
810     *
811     * <p>This is an <a href="package-summary.html#StreamOps">intermediate
812     * operation</a>.
813     *
814     * @return a {@code DoubleStream} consisting of the elements of this stream,
815     * converted to {@code double}
816     */
817    DoubleStream asDoubleStream();
818
819    /**
820     * Returns a {@code Stream} consisting of the elements of this stream,
821     * each boxed to an {@code Integer}.
822     *
823     * <p>This is an <a href="package-summary.html#StreamOps">intermediate
824     * operation</a>.
825     *
826     * @return a {@code Stream} consistent of the elements of this stream,
827     * each boxed to an {@code Integer}
828     */
829    Stream<Integer> boxed();
830
831    @Override
832    IntStream sequential();
833
834    @Override
835    IntStream parallel();
836
837    @Override
838    PrimitiveIterator.OfInt iterator();
839
840    @Override
841    Spliterator.OfInt spliterator();
842
843    // Static factories
844
845    /**
846     * Returns a builder for an {@code IntStream}.
847     *
848     * @return a stream builder
849     */
850    public static Builder builder() {
851        return new Streams.IntStreamBuilderImpl();
852    }
853
854    /**
855     * Returns an empty sequential {@code IntStream}.
856     *
857     * @return an empty sequential stream
858     */
859    public static IntStream empty() {
860        return StreamSupport.intStream(Spliterators.emptyIntSpliterator(), false);
861    }
862
863    /**
864     * Returns a sequential {@code IntStream} containing a single element.
865     *
866     * @param t the single element
867     * @return a singleton sequential stream
868     */
869    public static IntStream of(int t) {
870        return StreamSupport.intStream(new Streams.IntStreamBuilderImpl(t), false);
871    }
872
873    /**
874     * Returns a sequential ordered stream whose elements are the specified values.
875     *
876     * @param values the elements of the new stream
877     * @return the new stream
878     */
879    public static IntStream of(int... values) {
880        return Arrays.stream(values);
881    }
882
883    /**
884     * Returns an infinite sequential ordered {@code IntStream} produced by iterative
885     * application of a function {@code f} to an initial element {@code seed},
886     * producing a {@code Stream} consisting of {@code seed}, {@code f(seed)},
887     * {@code f(f(seed))}, etc.
888     *
889     * <p>The first element (position {@code 0}) in the {@code IntStream} will be
890     * the provided {@code seed}.  For {@code n > 0}, the element at position
891     * {@code n}, will be the result of applying the function {@code f} to the
892     * element at position {@code n - 1}.
893     *
894     * <p>The action of applying {@code f} for one element
895     * <a href="../concurrent/package-summary.html#MemoryVisibility"><i>happens-before</i></a>
896     * the action of applying {@code f} for subsequent elements.  For any given
897     * element the action may be performed in whatever thread the library
898     * chooses.
899     *
900     * @param seed the initial element
901     * @param f a function to be applied to the previous element to produce
902     *          a new element
903     * @return a new sequential {@code IntStream}
904     */
905    public static IntStream iterate(final int seed, final IntUnaryOperator f) {
906        Objects.requireNonNull(f);
907        Spliterator.OfInt spliterator = new Spliterators.AbstractIntSpliterator(Long.MAX_VALUE,
908               Spliterator.ORDERED | Spliterator.IMMUTABLE | Spliterator.NONNULL) {
909            int prev;
910            boolean started;
911
912            @Override
913            public boolean tryAdvance(IntConsumer action) {
914                Objects.requireNonNull(action);
915                int t;
916                if (started)
917                    t = f.applyAsInt(prev);
918                else {
919                    t = seed;
920                    started = true;
921                }
922                action.accept(prev = t);
923                return true;
924            }
925        };
926        return StreamSupport.intStream(spliterator, false);
927    }
928
929    /**
930     * Returns a sequential ordered {@code IntStream} produced by iterative
931     * application of the given {@code next} function to an initial element,
932     * conditioned on satisfying the given {@code hasNext} predicate.  The
933     * stream terminates as soon as the {@code hasNext} predicate returns false.
934     *
935     * <p>{@code IntStream.iterate} should produce the same sequence of elements as
936     * produced by the corresponding for-loop:
937     * <pre>{@code
938     *     for (int index=seed; hasNext.test(index); index = next.applyAsInt(index)) {
939     *         ...
940     *     }
941     * }</pre>
942     *
943     * <p>The resulting sequence may be empty if the {@code hasNext} predicate
944     * does not hold on the seed value.  Otherwise the first element will be the
945     * supplied {@code seed} value, the next element (if present) will be the
946     * result of applying the {@code next} function to the {@code seed} value,
947     * and so on iteratively until the {@code hasNext} predicate indicates that
948     * the stream should terminate.
949     *
950     * <p>The action of applying the {@code hasNext} predicate to an element
951     * <a href="../concurrent/package-summary.html#MemoryVisibility"><i>happens-before</i></a>
952     * the action of applying the {@code next} function to that element.  The
953     * action of applying the {@code next} function for one element
954     * <i>happens-before</i> the action of applying the {@code hasNext}
955     * predicate for subsequent elements.  For any given element an action may
956     * be performed in whatever thread the library chooses.
957     *
958     * @param seed the initial element
959     * @param hasNext a predicate to apply to elements to determine when the
960     *                stream must terminate.
961     * @param next a function to be applied to the previous element to produce
962     *             a new element
963     * @return a new sequential {@code IntStream}
964     * @since 9
965     */
966    public static IntStream iterate(int seed, IntPredicate hasNext, IntUnaryOperator next) {
967        Objects.requireNonNull(next);
968        Objects.requireNonNull(hasNext);
969        Spliterator.OfInt spliterator = new Spliterators.AbstractIntSpliterator(Long.MAX_VALUE,
970               Spliterator.ORDERED | Spliterator.IMMUTABLE | Spliterator.NONNULL) {
971            int prev;
972            boolean started, finished;
973
974            @Override
975            public boolean tryAdvance(IntConsumer action) {
976                Objects.requireNonNull(action);
977                if (finished)
978                    return false;
979                int t;
980                if (started)
981                    t = next.applyAsInt(prev);
982                else {
983                    t = seed;
984                    started = true;
985                }
986                if (!hasNext.test(t)) {
987                    finished = true;
988                    return false;
989                }
990                action.accept(prev = t);
991                return true;
992            }
993
994            @Override
995            public void forEachRemaining(IntConsumer action) {
996                Objects.requireNonNull(action);
997                if (finished)
998                    return;
999                finished = true;
1000                int t = started ? next.applyAsInt(prev) : seed;
1001                while (hasNext.test(t)) {
1002                    action.accept(t);
1003                    t = next.applyAsInt(t);
1004                }
1005            }
1006        };
1007        return StreamSupport.intStream(spliterator, false);
1008    }
1009
1010    /**
1011     * Returns an infinite sequential unordered stream where each element is
1012     * generated by the provided {@code IntSupplier}.  This is suitable for
1013     * generating constant streams, streams of random elements, etc.
1014     *
1015     * @param s the {@code IntSupplier} for generated elements
1016     * @return a new infinite sequential unordered {@code IntStream}
1017     */
1018    public static IntStream generate(IntSupplier s) {
1019        Objects.requireNonNull(s);
1020        return StreamSupport.intStream(
1021                new StreamSpliterators.InfiniteSupplyingSpliterator.OfInt(Long.MAX_VALUE, s), false);
1022    }
1023
1024    /**
1025     * Returns a sequential ordered {@code IntStream} from {@code startInclusive}
1026     * (inclusive) to {@code endExclusive} (exclusive) by an incremental step of
1027     * {@code 1}.
1028     *
1029     * @apiNote
1030     * <p>An equivalent sequence of increasing values can be produced
1031     * sequentially using a {@code for} loop as follows:
1032     * <pre>{@code
1033     *     for (int i = startInclusive; i < endExclusive ; i++) { ... }
1034     * }</pre>
1035     *
1036     * @param startInclusive the (inclusive) initial value
1037     * @param endExclusive the exclusive upper bound
1038     * @return a sequential {@code IntStream} for the range of {@code int}
1039     *         elements
1040     */
1041    public static IntStream range(int startInclusive, int endExclusive) {
1042        if (startInclusive >= endExclusive) {
1043            return empty();
1044        } else {
1045            return StreamSupport.intStream(
1046                    new Streams.RangeIntSpliterator(startInclusive, endExclusive, false), false);
1047        }
1048    }
1049
1050    /**
1051     * Returns a sequential ordered {@code IntStream} from {@code startInclusive}
1052     * (inclusive) to {@code endInclusive} (inclusive) by an incremental step of
1053     * {@code 1}.
1054     *
1055     * @apiNote
1056     * <p>An equivalent sequence of increasing values can be produced
1057     * sequentially using a {@code for} loop as follows:
1058     * <pre>{@code
1059     *     for (int i = startInclusive; i <= endInclusive ; i++) { ... }
1060     * }</pre>
1061     *
1062     * @param startInclusive the (inclusive) initial value
1063     * @param endInclusive the inclusive upper bound
1064     * @return a sequential {@code IntStream} for the range of {@code int}
1065     *         elements
1066     */
1067    public static IntStream rangeClosed(int startInclusive, int endInclusive) {
1068        if (startInclusive > endInclusive) {
1069            return empty();
1070        } else {
1071            return StreamSupport.intStream(
1072                    new Streams.RangeIntSpliterator(startInclusive, endInclusive, true), false);
1073        }
1074    }
1075
1076    /**
1077     * Creates a lazily concatenated stream whose elements are all the
1078     * elements of the first stream followed by all the elements of the
1079     * second stream.  The resulting stream is ordered if both
1080     * of the input streams are ordered, and parallel if either of the input
1081     * streams is parallel.  When the resulting stream is closed, the close
1082     * handlers for both input streams are invoked.
1083     *
1084     * @implNote
1085     * Use caution when constructing streams from repeated concatenation.
1086     * Accessing an element of a deeply concatenated stream can result in deep
1087     * call chains, or even {@code StackOverflowError}.
1088     *
1089     * @param a the first stream
1090     * @param b the second stream
1091     * @return the concatenation of the two input streams
1092     */
1093    public static IntStream concat(IntStream a, IntStream b) {
1094        Objects.requireNonNull(a);
1095        Objects.requireNonNull(b);
1096
1097        Spliterator.OfInt split = new Streams.ConcatSpliterator.OfInt(
1098                a.spliterator(), b.spliterator());
1099        IntStream stream = StreamSupport.intStream(split, a.isParallel() || b.isParallel());
1100        return stream.onClose(Streams.composedClose(a, b));
1101    }
1102
1103    /**
1104     * A mutable builder for an {@code IntStream}.
1105     *
1106     * <p>A stream builder has a lifecycle, which starts in a building
1107     * phase, during which elements can be added, and then transitions to a built
1108     * phase, after which elements may not be added.  The built phase
1109     * begins when the {@link #build()} method is called, which creates an
1110     * ordered stream whose elements are the elements that were added to the
1111     * stream builder, in the order they were added.
1112     *
1113     * @see IntStream#builder()
1114     * @since 1.8
1115     */
1116    public interface Builder extends IntConsumer {
1117
1118        /**
1119         * Adds an element to the stream being built.
1120         *
1121         * @throws IllegalStateException if the builder has already transitioned
1122         * to the built state
1123         */
1124        @Override
1125        void accept(int t);
1126
1127        /**
1128         * Adds an element to the stream being built.
1129         *
1130         * @implSpec
1131         * The default implementation behaves as if:
1132         * <pre>{@code
1133         *     accept(t)
1134         *     return this;
1135         * }</pre>
1136         *
1137         * @param t the element to add
1138         * @return {@code this} builder
1139         * @throws IllegalStateException if the builder has already transitioned
1140         * to the built state
1141         */
1142        default Builder add(int t) {
1143            accept(t);
1144            return this;
1145        }
1146
1147        /**
1148         * Builds the stream, transitioning this builder to the built state.
1149         * An {@code IllegalStateException} is thrown if there are further
1150         * attempts to operate on the builder after it has entered the built
1151         * state.
1152         *
1153         * @return the built stream
1154         * @throws IllegalStateException if the builder has already transitioned to
1155         * the built state
1156         */
1157        IntStream build();
1158    }
1159}
1160