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