1 /*
2  * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
4  *
5  * This code is free software; you can redistribute it and/or modify it
6  * under the terms of the GNU General Public License version 2 only, as
7  * published by the Free Software Foundation.  Oracle designates this
8  * particular file as subject to the "Classpath" exception as provided
9  * by Oracle in the LICENSE file that accompanied this code.
10  *
11  * This code is distributed in the hope that it will be useful, but WITHOUT
12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
14  * version 2 for more details (a copy is included in the LICENSE file that
15  * accompanied this code).
16  *
17  * You should have received a copy of the GNU General Public License version
18  * 2 along with this work; if not, write to the Free Software Foundation,
19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
20  *
21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
22  * or visit www.oracle.com if you need additional information or have any
23  * questions.
24  */
25 package java.util.stream;
26 
27 import java.util.Arrays;
28 import java.util.IntSummaryStatistics;
29 import java.util.Objects;
30 import java.util.OptionalDouble;
31 import java.util.OptionalInt;
32 import java.util.PrimitiveIterator;
33 import java.util.Spliterator;
34 import java.util.Spliterators;
35 import java.util.function.BiConsumer;
36 import java.util.function.Function;
37 import java.util.function.IntBinaryOperator;
38 import java.util.function.IntConsumer;
39 import java.util.function.IntFunction;
40 import java.util.function.IntPredicate;
41 import java.util.function.IntSupplier;
42 import java.util.function.IntToDoubleFunction;
43 import java.util.function.IntToLongFunction;
44 import java.util.function.IntUnaryOperator;
45 import java.util.function.ObjIntConsumer;
46 import 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  */
73 public 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      */
filter(IntPredicate predicate)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      */
map(IntUnaryOperator mapper)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      */
mapToObj(IntFunction<? extends U> mapper)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      */
mapToLong(IntToLongFunction mapper)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      */
mapToDouble(IntToDoubleFunction mapper)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      */
flatMap(IntFunction<? extends IntStream> mapper)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      */
distinct()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      */
sorted()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      * @param action a <a href="package-summary.html#NonInterference">
213      *               non-interfering</a> action to perform on the elements as
214      *               they are consumed from the stream
215      * @return the new stream
216      */
peek(IntConsumer action)217     IntStream peek(IntConsumer action);
218 
219     /**
220      * Returns a stream consisting of the elements of this stream, truncated
221      * to be no longer than {@code maxSize} in length.
222      *
223      * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting
224      * stateful intermediate operation</a>.
225      *
226      * @apiNote
227      * While {@code limit()} is generally a cheap operation on sequential
228      * stream pipelines, it can be quite expensive on ordered parallel pipelines,
229      * especially for large values of {@code maxSize}, since {@code limit(n)}
230      * is constrained to return not just any <em>n</em> elements, but the
231      * <em>first n</em> elements in the encounter order.  Using an unordered
232      * stream source (such as {@link #generate(IntSupplier)}) or removing the
233      * ordering constraint with {@link #unordered()} may result in significant
234      * speedups of {@code limit()} in parallel pipelines, if the semantics of
235      * your situation permit.  If consistency with encounter order is required,
236      * and you are experiencing poor performance or memory utilization with
237      * {@code limit()} in parallel pipelines, switching to sequential execution
238      * with {@link #sequential()} may improve performance.
239      *
240      * @param maxSize the number of elements the stream should be limited to
241      * @return the new stream
242      * @throws IllegalArgumentException if {@code maxSize} is negative
243      */
limit(long maxSize)244     IntStream limit(long maxSize);
245 
246     /**
247      * Returns a stream consisting of the remaining elements of this stream
248      * after discarding the first {@code n} elements of the stream.
249      * If this stream contains fewer than {@code n} elements then an
250      * empty stream will be returned.
251      *
252      * <p>This is a <a href="package-summary.html#StreamOps">stateful
253      * intermediate operation</a>.
254      *
255      * @apiNote
256      * While {@code skip()} is generally a cheap operation on sequential
257      * stream pipelines, it can be quite expensive on ordered parallel pipelines,
258      * especially for large values of {@code n}, since {@code skip(n)}
259      * is constrained to skip not just any <em>n</em> elements, but the
260      * <em>first n</em> elements in the encounter order.  Using an unordered
261      * stream source (such as {@link #generate(IntSupplier)}) or removing the
262      * ordering constraint with {@link #unordered()} may result in significant
263      * speedups of {@code skip()} in parallel pipelines, if the semantics of
264      * your situation permit.  If consistency with encounter order is required,
265      * and you are experiencing poor performance or memory utilization with
266      * {@code skip()} in parallel pipelines, switching to sequential execution
267      * with {@link #sequential()} may improve performance.
268      *
269      * @param n the number of leading elements to skip
270      * @return the new stream
271      * @throws IllegalArgumentException if {@code n} is negative
272      */
skip(long n)273     IntStream skip(long n);
274 
275     /**
276      * Performs an action for each element of this stream.
277      *
278      * <p>This is a <a href="package-summary.html#StreamOps">terminal
279      * operation</a>.
280      *
281      * <p>For parallel stream pipelines, this operation does <em>not</em>
282      * guarantee to respect the encounter order of the stream, as doing so
283      * would sacrifice the benefit of parallelism.  For any given element, the
284      * action may be performed at whatever time and in whatever thread the
285      * library chooses.  If the action accesses shared state, it is
286      * responsible for providing the required synchronization.
287      *
288      * @param action a <a href="package-summary.html#NonInterference">
289      *               non-interfering</a> action to perform on the elements
290      */
forEach(IntConsumer action)291     void forEach(IntConsumer action);
292 
293     /**
294      * Performs an action for each element of this stream, guaranteeing that
295      * each element is processed in encounter order for streams that have a
296      * defined encounter order.
297      *
298      * <p>This is a <a href="package-summary.html#StreamOps">terminal
299      * operation</a>.
300      *
301      * @param action a <a href="package-summary.html#NonInterference">
302      *               non-interfering</a> action to perform on the elements
303      * @see #forEach(IntConsumer)
304      */
forEachOrdered(IntConsumer action)305     void forEachOrdered(IntConsumer action);
306 
307     /**
308      * Returns an array containing the elements of this stream.
309      *
310      * <p>This is a <a href="package-summary.html#StreamOps">terminal
311      * operation</a>.
312      *
313      * @return an array containing the elements of this stream
314      */
toArray()315     int[] toArray();
316 
317     /**
318      * Performs a <a href="package-summary.html#Reduction">reduction</a> on the
319      * elements of this stream, using the provided identity value and an
320      * <a href="package-summary.html#Associativity">associative</a>
321      * accumulation function, and returns the reduced value.  This is equivalent
322      * to:
323      * <pre>{@code
324      *     int result = identity;
325      *     for (int element : this stream)
326      *         result = accumulator.applyAsInt(result, element)
327      *     return result;
328      * }</pre>
329      *
330      * but is not constrained to execute sequentially.
331      *
332      * <p>The {@code identity} value must be an identity for the accumulator
333      * function. This means that for all {@code x},
334      * {@code accumulator.apply(identity, x)} is equal to {@code x}.
335      * The {@code accumulator} function must be an
336      * <a href="package-summary.html#Associativity">associative</a> function.
337      *
338      * <p>This is a <a href="package-summary.html#StreamOps">terminal
339      * operation</a>.
340      *
341      * @apiNote Sum, min, max, and average are all special cases of reduction.
342      * Summing a stream of numbers can be expressed as:
343      *
344      * <pre>{@code
345      *     int sum = integers.reduce(0, (a, b) -> a+b);
346      * }</pre>
347      *
348      * or more compactly:
349      *
350      * <pre>{@code
351      *     int sum = integers.reduce(0, Integer::sum);
352      * }</pre>
353      *
354      * <p>While this may seem a more roundabout way to perform an aggregation
355      * compared to simply mutating a running total in a loop, reduction
356      * operations parallelize more gracefully, without needing additional
357      * synchronization and with greatly reduced risk of data races.
358      *
359      * @param identity the identity value for the accumulating function
360      * @param op an <a href="package-summary.html#Associativity">associative</a>,
361      *           <a href="package-summary.html#NonInterference">non-interfering</a>,
362      *           <a href="package-summary.html#Statelessness">stateless</a>
363      *           function for combining two values
364      * @return the result of the reduction
365      * @see #sum()
366      * @see #min()
367      * @see #max()
368      * @see #average()
369      */
reduce(int identity, IntBinaryOperator op)370     int reduce(int identity, IntBinaryOperator op);
371 
372     /**
373      * Performs a <a href="package-summary.html#Reduction">reduction</a> on the
374      * elements of this stream, using an
375      * <a href="package-summary.html#Associativity">associative</a> accumulation
376      * function, and returns an {@code OptionalInt} describing the reduced value,
377      * if any. This is equivalent to:
378      * <pre>{@code
379      *     boolean foundAny = false;
380      *     int result = null;
381      *     for (int element : this stream) {
382      *         if (!foundAny) {
383      *             foundAny = true;
384      *             result = element;
385      *         }
386      *         else
387      *             result = accumulator.applyAsInt(result, element);
388      *     }
389      *     return foundAny ? OptionalInt.of(result) : OptionalInt.empty();
390      * }</pre>
391      *
392      * but is not constrained to execute sequentially.
393      *
394      * <p>The {@code accumulator} function must be an
395      * <a href="package-summary.html#Associativity">associative</a> function.
396      *
397      * <p>This is a <a href="package-summary.html#StreamOps">terminal
398      * operation</a>.
399      *
400      * @param op an <a href="package-summary.html#Associativity">associative</a>,
401      *           <a href="package-summary.html#NonInterference">non-interfering</a>,
402      *           <a href="package-summary.html#Statelessness">stateless</a>
403      *           function for combining two values
404      * @return the result of the reduction
405      * @see #reduce(int, IntBinaryOperator)
406      */
reduce(IntBinaryOperator op)407     OptionalInt reduce(IntBinaryOperator op);
408 
409     /**
410      * Performs a <a href="package-summary.html#MutableReduction">mutable
411      * reduction</a> operation on the elements of this stream.  A mutable
412      * reduction is one in which the reduced value is a mutable result container,
413      * such as an {@code ArrayList}, and elements are incorporated by updating
414      * the state of the result rather than by replacing the result.  This
415      * produces a result equivalent to:
416      * <pre>{@code
417      *     R result = supplier.get();
418      *     for (int element : this stream)
419      *         accumulator.accept(result, element);
420      *     return result;
421      * }</pre>
422      *
423      * <p>Like {@link #reduce(int, IntBinaryOperator)}, {@code collect} operations
424      * can be parallelized without requiring additional synchronization.
425      *
426      * <p>This is a <a href="package-summary.html#StreamOps">terminal
427      * operation</a>.
428      *
429      * @param <R> type of the result
430      * @param supplier a function that creates a new result container. For a
431      *                 parallel execution, this function may be called
432      *                 multiple times and must return a fresh value each time.
433      * @param accumulator an <a href="package-summary.html#Associativity">associative</a>,
434      *                    <a href="package-summary.html#NonInterference">non-interfering</a>,
435      *                    <a href="package-summary.html#Statelessness">stateless</a>
436      *                    function for incorporating an additional element into a result
437      * @param combiner an <a href="package-summary.html#Associativity">associative</a>,
438      *                    <a href="package-summary.html#NonInterference">non-interfering</a>,
439      *                    <a href="package-summary.html#Statelessness">stateless</a>
440      *                    function for combining two values, which must be
441      *                    compatible with the accumulator function
442      * @return the result of the reduction
443      * @see Stream#collect(Supplier, BiConsumer, BiConsumer)
444      */
collect(Supplier<R> supplier, ObjIntConsumer<R> accumulator, BiConsumer<R, R> combiner)445     <R> R collect(Supplier<R> supplier,
446                   ObjIntConsumer<R> accumulator,
447                   BiConsumer<R, R> combiner);
448 
449     /**
450      * Returns the sum of elements in this stream.  This is a special case
451      * of a <a href="package-summary.html#Reduction">reduction</a>
452      * and is equivalent to:
453      * <pre>{@code
454      *     return reduce(0, Integer::sum);
455      * }</pre>
456      *
457      * <p>This is a <a href="package-summary.html#StreamOps">terminal
458      * operation</a>.
459      *
460      * @return the sum of elements in this stream
461      */
sum()462     int sum();
463 
464     /**
465      * Returns an {@code OptionalInt} describing the minimum element of this
466      * stream, or an empty optional if this stream is empty.  This is a special
467      * case of a <a href="package-summary.html#Reduction">reduction</a>
468      * and is equivalent to:
469      * <pre>{@code
470      *     return reduce(Integer::min);
471      * }</pre>
472      *
473      * <p>This is a <a href="package-summary.html#StreamOps">terminal operation</a>.
474      *
475      * @return an {@code OptionalInt} containing the minimum element of this
476      * stream, or an empty {@code OptionalInt} if the stream is empty
477      */
min()478     OptionalInt min();
479 
480     /**
481      * Returns an {@code OptionalInt} describing the maximum element of this
482      * stream, or an empty optional if this stream is empty.  This is a special
483      * case of a <a href="package-summary.html#Reduction">reduction</a>
484      * and is equivalent to:
485      * <pre>{@code
486      *     return reduce(Integer::max);
487      * }</pre>
488      *
489      * <p>This is a <a href="package-summary.html#StreamOps">terminal
490      * operation</a>.
491      *
492      * @return an {@code OptionalInt} containing the maximum element of this
493      * stream, or an empty {@code OptionalInt} if the stream is empty
494      */
max()495     OptionalInt max();
496 
497     /**
498      * Returns the count of elements in this stream.  This is a special case of
499      * a <a href="package-summary.html#Reduction">reduction</a> and is
500      * equivalent to:
501      * <pre>{@code
502      *     return mapToLong(e -> 1L).sum();
503      * }</pre>
504      *
505      * <p>This is a <a href="package-summary.html#StreamOps">terminal operation</a>.
506      *
507      * @return the count of elements in this stream
508      */
count()509     long count();
510 
511     /**
512      * Returns an {@code OptionalDouble} describing the arithmetic mean of elements of
513      * this stream, or an empty optional if this stream is empty.  This is a
514      * special case of a
515      * <a href="package-summary.html#Reduction">reduction</a>.
516      *
517      * <p>This is a <a href="package-summary.html#StreamOps">terminal
518      * operation</a>.
519      *
520      * @return an {@code OptionalDouble} containing the average element of this
521      * stream, or an empty optional if the stream is empty
522      */
average()523     OptionalDouble average();
524 
525     /**
526      * Returns an {@code IntSummaryStatistics} describing various
527      * summary data about the elements of this stream.  This is a special
528      * case of a <a href="package-summary.html#Reduction">reduction</a>.
529      *
530      * <p>This is a <a href="package-summary.html#StreamOps">terminal
531      * operation</a>.
532      *
533      * @return an {@code IntSummaryStatistics} describing various summary data
534      * about the elements of this stream
535      */
summaryStatistics()536     IntSummaryStatistics summaryStatistics();
537 
538     /**
539      * Returns whether any elements of this stream match the provided
540      * predicate.  May not evaluate the predicate on all elements if not
541      * necessary for determining the result.  If the stream is empty then
542      * {@code false} is returned and the predicate is not evaluated.
543      *
544      * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting
545      * terminal operation</a>.
546      *
547      * @apiNote
548      * This method evaluates the <em>existential quantification</em> of the
549      * predicate over the elements of the stream (for some x P(x)).
550      *
551      * @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>,
552      *                  <a href="package-summary.html#Statelessness">stateless</a>
553      *                  predicate to apply to elements of this stream
554      * @return {@code true} if any elements of the stream match the provided
555      * predicate, otherwise {@code false}
556      */
anyMatch(IntPredicate predicate)557     boolean anyMatch(IntPredicate predicate);
558 
559     /**
560      * Returns whether all elements of this stream match the provided predicate.
561      * May not evaluate the predicate on all elements if not necessary for
562      * determining the result.  If the stream is empty then {@code true} is
563      * returned and the predicate is not evaluated.
564      *
565      * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting
566      * terminal operation</a>.
567      *
568      * @apiNote
569      * This method evaluates the <em>universal quantification</em> of the
570      * predicate over the elements of the stream (for all x P(x)).  If the
571      * stream is empty, the quantification is said to be <em>vacuously
572      * satisfied</em> and is always {@code true} (regardless of P(x)).
573      *
574      * @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>,
575      *                  <a href="package-summary.html#Statelessness">stateless</a>
576      *                  predicate to apply to elements of this stream
577      * @return {@code true} if either all elements of the stream match the
578      * provided predicate or the stream is empty, otherwise {@code false}
579      */
allMatch(IntPredicate predicate)580     boolean allMatch(IntPredicate predicate);
581 
582     /**
583      * Returns whether no elements of this stream match the provided predicate.
584      * May not evaluate the predicate on all elements if not necessary for
585      * determining the result.  If the stream is empty then {@code true} is
586      * returned and the predicate is not evaluated.
587      *
588      * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting
589      * terminal operation</a>.
590      *
591      * @apiNote
592      * This method evaluates the <em>universal quantification</em> of the
593      * negated predicate over the elements of the stream (for all x ~P(x)).  If
594      * the stream is empty, the quantification is said to be vacuously satisfied
595      * and is always {@code true}, regardless of P(x).
596      *
597      * @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>,
598      *                  <a href="package-summary.html#Statelessness">stateless</a>
599      *                  predicate to apply to elements of this stream
600      * @return {@code true} if either no elements of the stream match the
601      * provided predicate or the stream is empty, otherwise {@code false}
602      */
noneMatch(IntPredicate predicate)603     boolean noneMatch(IntPredicate predicate);
604 
605     /**
606      * Returns an {@link OptionalInt} describing the first element of this
607      * stream, or an empty {@code OptionalInt} if the stream is empty.  If the
608      * stream has no encounter order, then any element may be returned.
609      *
610      * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting
611      * terminal operation</a>.
612      *
613      * @return an {@code OptionalInt} describing the first element of this stream,
614      * or an empty {@code OptionalInt} if the stream is empty
615      */
findFirst()616     OptionalInt findFirst();
617 
618     /**
619      * Returns an {@link OptionalInt} describing some element of the stream, or
620      * an empty {@code OptionalInt} if the stream is empty.
621      *
622      * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting
623      * terminal operation</a>.
624      *
625      * <p>The behavior of this operation is explicitly nondeterministic; it is
626      * free to select any element in the stream.  This is to allow for maximal
627      * performance in parallel operations; the cost is that multiple invocations
628      * on the same source may not return the same result.  (If a stable result
629      * is desired, use {@link #findFirst()} instead.)
630      *
631      * @return an {@code OptionalInt} describing some element of this stream, or
632      * an empty {@code OptionalInt} if the stream is empty
633      * @see #findFirst()
634      */
findAny()635     OptionalInt findAny();
636 
637     /**
638      * Returns a {@code LongStream} consisting of the elements of this stream,
639      * converted to {@code long}.
640      *
641      * <p>This is an <a href="package-summary.html#StreamOps">intermediate
642      * operation</a>.
643      *
644      * @return a {@code LongStream} consisting of the elements of this stream,
645      * converted to {@code long}
646      */
asLongStream()647     LongStream asLongStream();
648 
649     /**
650      * Returns a {@code DoubleStream} consisting of the elements of this stream,
651      * converted to {@code double}.
652      *
653      * <p>This is an <a href="package-summary.html#StreamOps">intermediate
654      * operation</a>.
655      *
656      * @return a {@code DoubleStream} consisting of the elements of this stream,
657      * converted to {@code double}
658      */
asDoubleStream()659     DoubleStream asDoubleStream();
660 
661     /**
662      * Returns a {@code Stream} consisting of the elements of this stream,
663      * each boxed to an {@code Integer}.
664      *
665      * <p>This is an <a href="package-summary.html#StreamOps">intermediate
666      * operation</a>.
667      *
668      * @return a {@code Stream} consistent of the elements of this stream,
669      * each boxed to an {@code Integer}
670      */
boxed()671     Stream<Integer> boxed();
672 
673     @Override
sequential()674     IntStream sequential();
675 
676     @Override
parallel()677     IntStream parallel();
678 
679     @Override
iterator()680     PrimitiveIterator.OfInt iterator();
681 
682     @Override
spliterator()683     Spliterator.OfInt spliterator();
684 
685     // Static factories
686 
687     /**
688      * Returns a builder for an {@code IntStream}.
689      *
690      * @return a stream builder
691      */
builder()692     public static Builder builder() {
693         return new Streams.IntStreamBuilderImpl();
694     }
695 
696     /**
697      * Returns an empty sequential {@code IntStream}.
698      *
699      * @return an empty sequential stream
700      */
empty()701     public static IntStream empty() {
702         return StreamSupport.intStream(Spliterators.emptyIntSpliterator(), false);
703     }
704 
705     /**
706      * Returns a sequential {@code IntStream} containing a single element.
707      *
708      * @param t the single element
709      * @return a singleton sequential stream
710      */
of(int t)711     public static IntStream of(int t) {
712         return StreamSupport.intStream(new Streams.IntStreamBuilderImpl(t), false);
713     }
714 
715     /**
716      * Returns a sequential ordered stream whose elements are the specified values.
717      *
718      * @param values the elements of the new stream
719      * @return the new stream
720      */
of(int... values)721     public static IntStream of(int... values) {
722         return Arrays.stream(values);
723     }
724 
725     /**
726      * Returns an infinite sequential ordered {@code IntStream} produced by iterative
727      * application of a function {@code f} to an initial element {@code seed},
728      * producing a {@code Stream} consisting of {@code seed}, {@code f(seed)},
729      * {@code f(f(seed))}, etc.
730      *
731      * <p>The first element (position {@code 0}) in the {@code IntStream} will be
732      * the provided {@code seed}.  For {@code n > 0}, the element at position
733      * {@code n}, will be the result of applying the function {@code f} to the
734      * element at position {@code n - 1}.
735      *
736      * @param seed the initial element
737      * @param f a function to be applied to to the previous element to produce
738      *          a new element
739      * @return A new sequential {@code IntStream}
740      */
iterate(final int seed, final IntUnaryOperator f)741     public static IntStream iterate(final int seed, final IntUnaryOperator f) {
742         Objects.requireNonNull(f);
743         final PrimitiveIterator.OfInt iterator = new PrimitiveIterator.OfInt() {
744             int t = seed;
745 
746             @Override
747             public boolean hasNext() {
748                 return true;
749             }
750 
751             @Override
752             public int nextInt() {
753                 int v = t;
754                 t = f.applyAsInt(t);
755                 return v;
756             }
757         };
758         return StreamSupport.intStream(Spliterators.spliteratorUnknownSize(
759                 iterator,
760                 Spliterator.ORDERED | Spliterator.IMMUTABLE | Spliterator.NONNULL), false);
761     }
762 
763     /**
764      * Returns an infinite sequential unordered stream where each element is
765      * generated by the provided {@code IntSupplier}.  This is suitable for
766      * generating constant streams, streams of random elements, etc.
767      *
768      * @param s the {@code IntSupplier} for generated elements
769      * @return a new infinite sequential unordered {@code IntStream}
770      */
generate(IntSupplier s)771     public static IntStream generate(IntSupplier s) {
772         Objects.requireNonNull(s);
773         return StreamSupport.intStream(
774                 new StreamSpliterators.InfiniteSupplyingSpliterator.OfInt(Long.MAX_VALUE, s), false);
775     }
776 
777     /**
778      * Returns a sequential ordered {@code IntStream} from {@code startInclusive}
779      * (inclusive) to {@code endExclusive} (exclusive) by an incremental step of
780      * {@code 1}.
781      *
782      * @apiNote
783      * <p>An equivalent sequence of increasing values can be produced
784      * sequentially using a {@code for} loop as follows:
785      * <pre>{@code
786      *     for (int i = startInclusive; i < endExclusive ; i++) { ... }
787      * }</pre>
788      *
789      * @param startInclusive the (inclusive) initial value
790      * @param endExclusive the exclusive upper bound
791      * @return a sequential {@code IntStream} for the range of {@code int}
792      *         elements
793      */
range(int startInclusive, int endExclusive)794     public static IntStream range(int startInclusive, int endExclusive) {
795         if (startInclusive >= endExclusive) {
796             return empty();
797         } else {
798             return StreamSupport.intStream(
799                     new Streams.RangeIntSpliterator(startInclusive, endExclusive, false), false);
800         }
801     }
802 
803     /**
804      * Returns a sequential ordered {@code IntStream} from {@code startInclusive}
805      * (inclusive) to {@code endInclusive} (inclusive) by an incremental step of
806      * {@code 1}.
807      *
808      * @apiNote
809      * <p>An equivalent sequence of increasing values can be produced
810      * sequentially using a {@code for} loop as follows:
811      * <pre>{@code
812      *     for (int i = startInclusive; i <= endInclusive ; i++) { ... }
813      * }</pre>
814      *
815      * @param startInclusive the (inclusive) initial value
816      * @param endInclusive the inclusive upper bound
817      * @return a sequential {@code IntStream} for the range of {@code int}
818      *         elements
819      */
rangeClosed(int startInclusive, int endInclusive)820     public static IntStream rangeClosed(int startInclusive, int endInclusive) {
821         if (startInclusive > endInclusive) {
822             return empty();
823         } else {
824             return StreamSupport.intStream(
825                     new Streams.RangeIntSpliterator(startInclusive, endInclusive, true), false);
826         }
827     }
828 
829     /**
830      * Creates a lazily concatenated stream whose elements are all the
831      * elements of the first stream followed by all the elements of the
832      * second stream.  The resulting stream is ordered if both
833      * of the input streams are ordered, and parallel if either of the input
834      * streams is parallel.  When the resulting stream is closed, the close
835      * handlers for both input streams are invoked.
836      *
837      * @implNote
838      * Use caution when constructing streams from repeated concatenation.
839      * Accessing an element of a deeply concatenated stream can result in deep
840      * call chains, or even {@code StackOverflowException}.
841      *
842      * @param a the first stream
843      * @param b the second stream
844      * @return the concatenation of the two input streams
845      */
concat(IntStream a, IntStream b)846     public static IntStream concat(IntStream a, IntStream b) {
847         Objects.requireNonNull(a);
848         Objects.requireNonNull(b);
849 
850         Spliterator.OfInt split = new Streams.ConcatSpliterator.OfInt(
851                 a.spliterator(), b.spliterator());
852         IntStream stream = StreamSupport.intStream(split, a.isParallel() || b.isParallel());
853         return stream.onClose(Streams.composedClose(a, b));
854     }
855 
856     /**
857      * A mutable builder for an {@code IntStream}.
858      *
859      * <p>A stream builder has a lifecycle, which starts in a building
860      * phase, during which elements can be added, and then transitions to a built
861      * phase, after which elements may not be added.  The built phase
862      * begins when the {@link #build()} method is called, which creates an
863      * ordered stream whose elements are the elements that were added to the
864      * stream builder, in the order they were added.
865      *
866      * @see IntStream#builder()
867      * @since 1.8
868      */
869     public interface Builder extends IntConsumer {
870 
871         /**
872          * Adds an element to the stream being built.
873          *
874          * @throws IllegalStateException if the builder has already transitioned
875          * to the built state
876          */
877         @Override
accept(int t)878         void accept(int t);
879 
880         /**
881          * Adds an element to the stream being built.
882          *
883          * @implSpec
884          * The default implementation behaves as if:
885          * <pre>{@code
886          *     accept(t)
887          *     return this;
888          * }</pre>
889          *
890          * @param t the element to add
891          * @return {@code this} builder
892          * @throws IllegalStateException if the builder has already transitioned
893          * to the built state
894          */
add(int t)895         default Builder add(int t) {
896             accept(t);
897             return this;
898         }
899 
900         /**
901          * Builds the stream, transitioning this builder to the built state.
902          * An {@code IllegalStateException} is thrown if there are further
903          * attempts to operate on the builder after it has entered the built
904          * state.
905          *
906          * @return the built stream
907          * @throws IllegalStateException if the builder has already transitioned to
908          * the built state
909          */
build()910         IntStream build();
911     }
912 }
913