• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 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.LongSummaryStatistics;
33 import java.util.Objects;
34 import java.util.OptionalDouble;
35 import java.util.OptionalLong;
36 import java.util.PrimitiveIterator;
37 import java.util.Spliterator;
38 import java.util.Spliterators;
39 import java.util.concurrent.ConcurrentHashMap;
40 import java.util.function.BiConsumer;
41 import java.util.function.Function;
42 import java.util.function.LongBinaryOperator;
43 import java.util.function.LongConsumer;
44 import java.util.function.LongFunction;
45 import java.util.function.LongPredicate;
46 import java.util.function.LongSupplier;
47 import java.util.function.LongToDoubleFunction;
48 import java.util.function.LongToIntFunction;
49 import java.util.function.LongUnaryOperator;
50 import java.util.function.ObjLongConsumer;
51 import java.util.function.Supplier;
52 
53 /**
54  * A sequence of primitive long-valued elements supporting sequential and parallel
55  * aggregate operations.  This is the {@code long} primitive specialization of
56  * {@link Stream}.
57  *
58  * <p>The following example illustrates an aggregate operation using
59  * {@link Stream} and {@link LongStream}, computing the sum of the weights of the
60  * red widgets:
61  *
62  * <pre>{@code
63  *     long sum = widgets.stream()
64  *                       .filter(w -> w.getColor() == RED)
65  *                       .mapToLong(w -> w.getWeight())
66  *                       .sum();
67  * }</pre>
68  *
69  * See the class documentation for {@link Stream} and the package documentation
70  * for <a href="package-summary.html">java.util.stream</a> for additional
71  * specification of streams, stream operations, stream pipelines, and
72  * parallelism.
73  *
74  * @since 1.8
75  * @see Stream
76  * @see <a href="package-summary.html">java.util.stream</a>
77  */
78 public interface LongStream extends BaseStream<Long, LongStream> {
79 
80     /**
81      * Returns a stream consisting of the elements of this stream that match
82      * the given predicate.
83      *
84      * <p>This is an <a href="package-summary.html#StreamOps">intermediate
85      * operation</a>.
86      *
87      * @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>,
88      *                  <a href="package-summary.html#Statelessness">stateless</a>
89      *                  predicate to apply to each element to determine if it
90      *                  should be included
91      * @return the new stream
92      */
filter(LongPredicate predicate)93     LongStream filter(LongPredicate predicate);
94 
95     /**
96      * Returns a stream consisting of the results of applying the given
97      * function to the elements of this stream.
98      *
99      * <p>This is an <a href="package-summary.html#StreamOps">intermediate
100      * operation</a>.
101      *
102      * @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>,
103      *               <a href="package-summary.html#Statelessness">stateless</a>
104      *               function to apply to each element
105      * @return the new stream
106      */
map(LongUnaryOperator mapper)107     LongStream map(LongUnaryOperator mapper);
108 
109     /**
110      * Returns an object-valued {@code Stream} consisting of the results of
111      * applying the given function to the elements of this stream.
112      *
113      * <p>This is an <a href="package-summary.html#StreamOps">
114      *     intermediate operation</a>.
115      *
116      * @param <U> the element type of the new stream
117      * @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>,
118      *               <a href="package-summary.html#Statelessness">stateless</a>
119      *               function to apply to each element
120      * @return the new stream
121      */
mapToObj(LongFunction<? extends U> mapper)122     <U> Stream<U> mapToObj(LongFunction<? extends U> mapper);
123 
124     /**
125      * Returns an {@code IntStream} consisting of the results of applying the
126      * given function to the elements of this stream.
127      *
128      * <p>This is an <a href="package-summary.html#StreamOps">intermediate
129      * operation</a>.
130      *
131      * @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>,
132      *               <a href="package-summary.html#Statelessness">stateless</a>
133      *               function to apply to each element
134      * @return the new stream
135      */
mapToInt(LongToIntFunction mapper)136     IntStream mapToInt(LongToIntFunction mapper);
137 
138     /**
139      * Returns a {@code DoubleStream} consisting of the results of applying the
140      * given function to the elements of this stream.
141      *
142      * <p>This is an <a href="package-summary.html#StreamOps">intermediate
143      * operation</a>.
144      *
145      * @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>,
146      *               <a href="package-summary.html#Statelessness">stateless</a>
147      *               function to apply to each element
148      * @return the new stream
149      */
mapToDouble(LongToDoubleFunction mapper)150     DoubleStream mapToDouble(LongToDoubleFunction mapper);
151 
152     /**
153      * Returns a stream consisting of the results of replacing each element of
154      * this stream with the contents of a mapped stream produced by applying
155      * the provided mapping function to each element.  Each mapped stream is
156      * {@link java.util.stream.BaseStream#close() closed} after its contents
157      * have been placed into this stream.  (If a mapped stream is {@code null}
158      * an empty stream is used, instead.)
159      *
160      * <p>This is an <a href="package-summary.html#StreamOps">intermediate
161      * operation</a>.
162      *
163      * @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>,
164      *               <a href="package-summary.html#Statelessness">stateless</a>
165      *               function to apply to each element which produces a
166      *               {@code LongStream} of new values
167      * @return the new stream
168      * @see Stream#flatMap(Function)
169      */
flatMap(LongFunction<? extends LongStream> mapper)170     LongStream flatMap(LongFunction<? extends LongStream> mapper);
171 
172     /**
173      * Returns a stream consisting of the distinct elements of this stream.
174      *
175      * <p>This is a <a href="package-summary.html#StreamOps">stateful
176      * intermediate operation</a>.
177      *
178      * @return the new stream
179      */
distinct()180     LongStream distinct();
181 
182     /**
183      * Returns a stream consisting of the elements of this stream in sorted
184      * order.
185      *
186      * <p>This is a <a href="package-summary.html#StreamOps">stateful
187      * intermediate operation</a>.
188      *
189      * @return the new stream
190      */
sorted()191     LongStream sorted();
192 
193     /**
194      * Returns a stream consisting of the elements of this stream, additionally
195      * performing the provided action on each element as elements are consumed
196      * from the resulting stream.
197      *
198      * <p>This is an <a href="package-summary.html#StreamOps">intermediate
199      * operation</a>.
200      *
201      * <p>For parallel stream pipelines, the action may be called at
202      * whatever time and in whatever thread the element is made available by the
203      * upstream operation.  If the action modifies shared state,
204      * it is responsible for providing the required synchronization.
205      *
206      * @apiNote This method exists mainly to support debugging, where you want
207      * to see the elements as they flow past a certain point in a pipeline:
208      * <pre>{@code
209      *     LongStream.of(1, 2, 3, 4)
210      *         .filter(e -> e > 2)
211      *         .peek(e -> System.out.println("Filtered value: " + e))
212      *         .map(e -> e * e)
213      *         .peek(e -> System.out.println("Mapped value: " + e))
214      *         .sum();
215      * }</pre>
216      *
217      * @param action a <a href="package-summary.html#NonInterference">
218      *               non-interfering</a> action to perform on the elements as
219      *               they are consumed from the stream
220      * @return the new stream
221      */
peek(LongConsumer action)222     LongStream peek(LongConsumer action);
223 
224     /**
225      * Returns a stream consisting of the elements of this stream, truncated
226      * to be no longer than {@code maxSize} in length.
227      *
228      * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting
229      * stateful intermediate operation</a>.
230      *
231      * @apiNote
232      * While {@code limit()} is generally a cheap operation on sequential
233      * stream pipelines, it can be quite expensive on ordered parallel pipelines,
234      * especially for large values of {@code maxSize}, since {@code limit(n)}
235      * is constrained to return not just any <em>n</em> elements, but the
236      * <em>first n</em> elements in the encounter order.  Using an unordered
237      * stream source (such as {@link #generate(LongSupplier)}) or removing the
238      * ordering constraint with {@link #unordered()} may result in significant
239      * speedups of {@code limit()} in parallel pipelines, if the semantics of
240      * your situation permit.  If consistency with encounter order is required,
241      * and you are experiencing poor performance or memory utilization with
242      * {@code limit()} in parallel pipelines, switching to sequential execution
243      * with {@link #sequential()} may improve performance.
244      *
245      * @param maxSize the number of elements the stream should be limited to
246      * @return the new stream
247      * @throws IllegalArgumentException if {@code maxSize} is negative
248      */
limit(long maxSize)249     LongStream limit(long maxSize);
250 
251     /**
252      * Returns a stream consisting of the remaining elements of this stream
253      * after discarding the first {@code n} elements of the stream.
254      * If this stream contains fewer than {@code n} elements then an
255      * empty stream will be returned.
256      *
257      * <p>This is a <a href="package-summary.html#StreamOps">stateful
258      * intermediate operation</a>.
259      *
260      * @apiNote
261      * While {@code skip()} is generally a cheap operation on sequential
262      * stream pipelines, it can be quite expensive on ordered parallel pipelines,
263      * especially for large values of {@code n}, since {@code skip(n)}
264      * is constrained to skip not just any <em>n</em> elements, but the
265      * <em>first n</em> elements in the encounter order.  Using an unordered
266      * stream source (such as {@link #generate(LongSupplier)}) or removing the
267      * ordering constraint with {@link #unordered()} may result in significant
268      * speedups of {@code skip()} in parallel pipelines, if the semantics of
269      * your situation permit.  If consistency with encounter order is required,
270      * and you are experiencing poor performance or memory utilization with
271      * {@code skip()} in parallel pipelines, switching to sequential execution
272      * with {@link #sequential()} may improve performance.
273      *
274      * @param n the number of leading elements to skip
275      * @return the new stream
276      * @throws IllegalArgumentException if {@code n} is negative
277      */
skip(long n)278     LongStream skip(long n);
279 
280     /**
281      * Performs an action for each element of this stream.
282      *
283      * <p>This is a <a href="package-summary.html#StreamOps">terminal
284      * operation</a>.
285      *
286      * <p>For parallel stream pipelines, this operation does <em>not</em>
287      * guarantee to respect the encounter order of the stream, as doing so
288      * would sacrifice the benefit of parallelism.  For any given element, the
289      * action may be performed at whatever time and in whatever thread the
290      * library chooses.  If the action accesses shared state, it is
291      * responsible for providing the required synchronization.
292      *
293      * @param action a <a href="package-summary.html#NonInterference">
294      *               non-interfering</a> action to perform on the elements
295      */
forEach(LongConsumer action)296     void forEach(LongConsumer action);
297 
298     /**
299      * Performs an action for each element of this stream, guaranteeing that
300      * each element is processed in encounter order for streams that have a
301      * defined encounter order.
302      *
303      * <p>This is a <a href="package-summary.html#StreamOps">terminal
304      * operation</a>.
305      *
306      * @param action a <a href="package-summary.html#NonInterference">
307      *               non-interfering</a> action to perform on the elements
308      * @see #forEach(LongConsumer)
309      */
forEachOrdered(LongConsumer action)310     void forEachOrdered(LongConsumer action);
311 
312     /**
313      * Returns an array containing the elements of this stream.
314      *
315      * <p>This is a <a href="package-summary.html#StreamOps">terminal
316      * operation</a>.
317      *
318      * @return an array containing the elements of this stream
319      */
toArray()320     long[] toArray();
321 
322     /**
323      * Performs a <a href="package-summary.html#Reduction">reduction</a> on the
324      * elements of this stream, using the provided identity value and an
325      * <a href="package-summary.html#Associativity">associative</a>
326      * accumulation function, and returns the reduced value.  This is equivalent
327      * to:
328      * <pre>{@code
329      *     long result = identity;
330      *     for (long element : this stream)
331      *         result = accumulator.applyAsLong(result, element)
332      *     return result;
333      * }</pre>
334      *
335      * but is not constrained to execute sequentially.
336      *
337      * <p>The {@code identity} value must be an identity for the accumulator
338      * function. This means that for all {@code x},
339      * {@code accumulator.apply(identity, x)} is equal to {@code x}.
340      * The {@code accumulator} function must be an
341      * <a href="package-summary.html#Associativity">associative</a> function.
342      *
343      * <p>This is a <a href="package-summary.html#StreamOps">terminal
344      * operation</a>.
345      *
346      * @apiNote Sum, min, max, and average are all special cases of reduction.
347      * Summing a stream of numbers can be expressed as:
348      *
349      * <pre>{@code
350      *     long sum = integers.reduce(0, (a, b) -> a+b);
351      * }</pre>
352      *
353      * or more compactly:
354      *
355      * <pre>{@code
356      *     long sum = integers.reduce(0, Long::sum);
357      * }</pre>
358      *
359      * <p>While this may seem a more roundabout way to perform an aggregation
360      * compared to simply mutating a running total in a loop, reduction
361      * operations parallelize more gracefully, without needing additional
362      * synchronization and with greatly reduced risk of data races.
363      *
364      * @param identity the identity value for the accumulating function
365      * @param op an <a href="package-summary.html#Associativity">associative</a>,
366      *           <a href="package-summary.html#NonInterference">non-interfering</a>,
367      *           <a href="package-summary.html#Statelessness">stateless</a>
368      *           function for combining two values
369      * @return the result of the reduction
370      * @see #sum()
371      * @see #min()
372      * @see #max()
373      * @see #average()
374      */
reduce(long identity, LongBinaryOperator op)375     long reduce(long identity, LongBinaryOperator op);
376 
377     /**
378      * Performs a <a href="package-summary.html#Reduction">reduction</a> on the
379      * elements of this stream, using an
380      * <a href="package-summary.html#Associativity">associative</a> accumulation
381      * function, and returns an {@code OptionalLong} describing the reduced value,
382      * if any. This is equivalent to:
383      * <pre>{@code
384      *     boolean foundAny = false;
385      *     long result = null;
386      *     for (long element : this stream) {
387      *         if (!foundAny) {
388      *             foundAny = true;
389      *             result = element;
390      *         }
391      *         else
392      *             result = accumulator.applyAsLong(result, element);
393      *     }
394      *     return foundAny ? OptionalLong.of(result) : OptionalLong.empty();
395      * }</pre>
396      *
397      * but is not constrained to execute sequentially.
398      *
399      * <p>The {@code accumulator} function must be an
400      * <a href="package-summary.html#Associativity">associative</a> function.
401      *
402      * <p>This is a <a href="package-summary.html#StreamOps">terminal
403      * operation</a>.
404      *
405      * @param op an <a href="package-summary.html#Associativity">associative</a>,
406      *           <a href="package-summary.html#NonInterference">non-interfering</a>,
407      *           <a href="package-summary.html#Statelessness">stateless</a>
408      *           function for combining two values
409      * @return the result of the reduction
410      * @see #reduce(long, LongBinaryOperator)
411      */
reduce(LongBinaryOperator op)412     OptionalLong reduce(LongBinaryOperator op);
413 
414     /**
415      * Performs a <a href="package-summary.html#MutableReduction">mutable
416      * reduction</a> operation on the elements of this stream.  A mutable
417      * reduction is one in which the reduced value is a mutable result container,
418      * such as an {@code ArrayList}, and elements are incorporated by updating
419      * the state of the result rather than by replacing the result.  This
420      * produces a result equivalent to:
421      * <pre>{@code
422      *     R result = supplier.get();
423      *     for (long element : this stream)
424      *         accumulator.accept(result, element);
425      *     return result;
426      * }</pre>
427      *
428      * <p>Like {@link #reduce(long, LongBinaryOperator)}, {@code collect} operations
429      * can be parallelized without requiring additional synchronization.
430      *
431      * <p>This is a <a href="package-summary.html#StreamOps">terminal
432      * operation</a>.
433      *
434      * @param <R> type of the result
435      * @param supplier a function that creates a new result container. For a
436      *                 parallel execution, this function may be called
437      *                 multiple times and must return a fresh value each time.
438      * @param accumulator an <a href="package-summary.html#Associativity">associative</a>,
439      *                    <a href="package-summary.html#NonInterference">non-interfering</a>,
440      *                    <a href="package-summary.html#Statelessness">stateless</a>
441      *                    function for incorporating an additional element into a result
442      * @param combiner an <a href="package-summary.html#Associativity">associative</a>,
443      *                    <a href="package-summary.html#NonInterference">non-interfering</a>,
444      *                    <a href="package-summary.html#Statelessness">stateless</a>
445      *                    function for combining two values, which must be
446      *                    compatible with the accumulator function
447      * @return the result of the reduction
448      * @see Stream#collect(Supplier, BiConsumer, BiConsumer)
449      */
collect(Supplier<R> supplier, ObjLongConsumer<R> accumulator, BiConsumer<R, R> combiner)450     <R> R collect(Supplier<R> supplier,
451                   ObjLongConsumer<R> accumulator,
452                   BiConsumer<R, R> combiner);
453 
454     /**
455      * Returns the sum of elements in this stream.  This is a special case
456      * of a <a href="package-summary.html#Reduction">reduction</a>
457      * and is equivalent to:
458      * <pre>{@code
459      *     return reduce(0, Long::sum);
460      * }</pre>
461      *
462      * <p>This is a <a href="package-summary.html#StreamOps">terminal
463      * operation</a>.
464      *
465      * @return the sum of elements in this stream
466      */
sum()467     long sum();
468 
469     /**
470      * Returns an {@code OptionalLong} describing the minimum element of this
471      * stream, or an empty optional if this stream is empty.  This is a special
472      * case of a <a href="package-summary.html#Reduction">reduction</a>
473      * and is equivalent to:
474      * <pre>{@code
475      *     return reduce(Long::min);
476      * }</pre>
477      *
478      * <p>This is a <a href="package-summary.html#StreamOps">terminal operation</a>.
479      *
480      * @return an {@code OptionalLong} containing the minimum element of this
481      * stream, or an empty {@code OptionalLong} if the stream is empty
482      */
min()483     OptionalLong min();
484 
485     /**
486      * Returns an {@code OptionalLong} describing the maximum element of this
487      * stream, or an empty optional if this stream is empty.  This is a special
488      * case of a <a href="package-summary.html#Reduction">reduction</a>
489      * and is equivalent to:
490      * <pre>{@code
491      *     return reduce(Long::max);
492      * }</pre>
493      *
494      * <p>This is a <a href="package-summary.html#StreamOps">terminal
495      * operation</a>.
496      *
497      * @return an {@code OptionalLong} containing the maximum element of this
498      * stream, or an empty {@code OptionalLong} if the stream is empty
499      */
max()500     OptionalLong max();
501 
502     /**
503      * Returns the count of elements in this stream.  This is a special case of
504      * a <a href="package-summary.html#Reduction">reduction</a> and is
505      * equivalent to:
506      * <pre>{@code
507      *     return map(e -> 1L).sum();
508      * }</pre>
509      *
510      * <p>This is a <a href="package-summary.html#StreamOps">terminal operation</a>.
511      *
512      * @return the count of elements in this stream
513      */
count()514     long count();
515 
516     /**
517      * Returns an {@code OptionalDouble} describing the arithmetic mean of elements of
518      * this stream, or an empty optional if this stream is empty.  This is a
519      * special case of a
520      * <a href="package-summary.html#Reduction">reduction</a>.
521      *
522      * <p>This is a <a href="package-summary.html#StreamOps">terminal
523      * operation</a>.
524      *
525      * @return an {@code OptionalDouble} containing the average element of this
526      * stream, or an empty optional if the stream is empty
527      */
average()528     OptionalDouble average();
529 
530     /**
531      * Returns a {@code LongSummaryStatistics} describing various summary data
532      * about the elements of this stream.  This is a special case of a
533      * <a href="package-summary.html#Reduction">reduction</a>.
534      *
535      * <p>This is a <a href="package-summary.html#StreamOps">terminal
536      * operation</a>.
537      *
538      * @return a {@code LongSummaryStatistics} describing various summary data
539      * about the elements of this stream
540      */
summaryStatistics()541     LongSummaryStatistics summaryStatistics();
542 
543     /**
544      * Returns whether any elements of this stream match the provided
545      * predicate.  May not evaluate the predicate on all elements if not
546      * necessary for determining the result.  If the stream is empty then
547      * {@code false} is returned and the predicate is not evaluated.
548      *
549      * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting
550      * terminal operation</a>.
551      *
552      * @apiNote
553      * This method evaluates the <em>existential quantification</em> of the
554      * predicate over the elements of the stream (for some x P(x)).
555      *
556      * @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>,
557      *                  <a href="package-summary.html#Statelessness">stateless</a>
558      *                  predicate to apply to elements of this stream
559      * @return {@code true} if any elements of the stream match the provided
560      * predicate, otherwise {@code false}
561      */
anyMatch(LongPredicate predicate)562     boolean anyMatch(LongPredicate predicate);
563 
564     /**
565      * Returns whether all elements of this stream match the provided predicate.
566      * May not evaluate the predicate on all elements if not necessary for
567      * determining the result.  If the stream is empty then {@code true} is
568      * returned and the predicate is not evaluated.
569      *
570      * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting
571      * terminal operation</a>.
572      *
573      * @apiNote
574      * This method evaluates the <em>universal quantification</em> of the
575      * predicate over the elements of the stream (for all x P(x)).  If the
576      * stream is empty, the quantification is said to be <em>vacuously
577      * satisfied</em> and is always {@code true} (regardless of P(x)).
578      *
579      * @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>,
580      *                  <a href="package-summary.html#Statelessness">stateless</a>
581      *                  predicate to apply to elements of this stream
582      * @return {@code true} if either all elements of the stream match the
583      * provided predicate or the stream is empty, otherwise {@code false}
584      */
allMatch(LongPredicate predicate)585     boolean allMatch(LongPredicate predicate);
586 
587     /**
588      * Returns whether no elements of this stream match the provided predicate.
589      * May not evaluate the predicate on all elements if not necessary for
590      * determining the result.  If the stream is empty then {@code true} is
591      * returned and the predicate is not evaluated.
592      *
593      * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting
594      * terminal operation</a>.
595      *
596      * @apiNote
597      * This method evaluates the <em>universal quantification</em> of the
598      * negated predicate over the elements of the stream (for all x ~P(x)).  If
599      * the stream is empty, the quantification is said to be vacuously satisfied
600      * and is always {@code true}, regardless of P(x).
601      *
602      * @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>,
603      *                  <a href="package-summary.html#Statelessness">stateless</a>
604      *                  predicate to apply to elements of this stream
605      * @return {@code true} if either no elements of the stream match the
606      * provided predicate or the stream is empty, otherwise {@code false}
607      */
noneMatch(LongPredicate predicate)608     boolean noneMatch(LongPredicate predicate);
609 
610     /**
611      * Returns an {@link OptionalLong} describing the first element of this
612      * stream, or an empty {@code OptionalLong} if the stream is empty.  If the
613      * stream has no encounter order, then any element may be returned.
614      *
615      * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting
616      * terminal operation</a>.
617      *
618      * @return an {@code OptionalLong} describing the first element of this
619      * stream, or an empty {@code OptionalLong} if the stream is empty
620      */
findFirst()621     OptionalLong findFirst();
622 
623     /**
624      * Returns an {@link OptionalLong} describing some element of the stream, or
625      * an empty {@code OptionalLong} if the stream is empty.
626      *
627      * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting
628      * terminal operation</a>.
629      *
630      * <p>The behavior of this operation is explicitly nondeterministic; it is
631      * free to select any element in the stream.  This is to allow for maximal
632      * performance in parallel operations; the cost is that multiple invocations
633      * on the same source may not return the same result.  (If a stable result
634      * is desired, use {@link #findFirst()} instead.)
635      *
636      * @return an {@code OptionalLong} describing some element of this stream,
637      * or an empty {@code OptionalLong} if the stream is empty
638      * @see #findFirst()
639      */
findAny()640     OptionalLong findAny();
641 
642     /**
643      * Returns a {@code DoubleStream} consisting of the elements of this stream,
644      * converted to {@code double}.
645      *
646      * <p>This is an <a href="package-summary.html#StreamOps">intermediate
647      * operation</a>.
648      *
649      * @return a {@code DoubleStream} consisting of the elements of this stream,
650      * converted to {@code double}
651      */
asDoubleStream()652     DoubleStream asDoubleStream();
653 
654     /**
655      * Returns a {@code Stream} consisting of the elements of this stream,
656      * each boxed to a {@code Long}.
657      *
658      * <p>This is an <a href="package-summary.html#StreamOps">intermediate
659      * operation</a>.
660      *
661      * @return a {@code Stream} consistent of the elements of this stream,
662      * each boxed to {@code Long}
663      */
boxed()664     Stream<Long> boxed();
665 
666     @Override
sequential()667     LongStream sequential();
668 
669     @Override
parallel()670     LongStream parallel();
671 
672     @Override
iterator()673     PrimitiveIterator.OfLong iterator();
674 
675     @Override
spliterator()676     Spliterator.OfLong spliterator();
677 
678     // Static factories
679 
680     /**
681      * Returns a builder for a {@code LongStream}.
682      *
683      * @return a stream builder
684      */
builder()685     public static Builder builder() {
686         return new Streams.LongStreamBuilderImpl();
687     }
688 
689     /**
690      * Returns an empty sequential {@code LongStream}.
691      *
692      * @return an empty sequential stream
693      */
empty()694     public static LongStream empty() {
695         return StreamSupport.longStream(Spliterators.emptyLongSpliterator(), false);
696     }
697 
698     /**
699      * Returns a sequential {@code LongStream} containing a single element.
700      *
701      * @param t the single element
702      * @return a singleton sequential stream
703      */
of(long t)704     public static LongStream of(long t) {
705         return StreamSupport.longStream(new Streams.LongStreamBuilderImpl(t), false);
706     }
707 
708     /**
709      * Returns a sequential ordered stream whose elements are the specified values.
710      *
711      * @param values the elements of the new stream
712      * @return the new stream
713      */
of(long... values)714     public static LongStream of(long... values) {
715         return Arrays.stream(values);
716     }
717 
718     /**
719      * Returns an infinite sequential ordered {@code LongStream} produced by iterative
720      * application of a function {@code f} to an initial element {@code seed},
721      * producing a {@code Stream} consisting of {@code seed}, {@code f(seed)},
722      * {@code f(f(seed))}, etc.
723      *
724      * <p>The first element (position {@code 0}) in the {@code LongStream} will
725      * be the provided {@code seed}.  For {@code n > 0}, the element at position
726      * {@code n}, will be the result of applying the function {@code f} to the
727      * element at position {@code n - 1}.
728      *
729      * @param seed the initial element
730      * @param f a function to be applied to to the previous element to produce
731      *          a new element
732      * @return a new sequential {@code LongStream}
733      */
iterate(final long seed, final LongUnaryOperator f)734     public static LongStream iterate(final long seed, final LongUnaryOperator f) {
735         Objects.requireNonNull(f);
736         final PrimitiveIterator.OfLong iterator = new PrimitiveIterator.OfLong() {
737             long t = seed;
738 
739             @Override
740             public boolean hasNext() {
741                 return true;
742             }
743 
744             @Override
745             public long nextLong() {
746                 long v = t;
747                 t = f.applyAsLong(t);
748                 return v;
749             }
750         };
751         return StreamSupport.longStream(Spliterators.spliteratorUnknownSize(
752                 iterator,
753                 Spliterator.ORDERED | Spliterator.IMMUTABLE | Spliterator.NONNULL), false);
754     }
755 
756     /**
757      * Returns an infinite sequential unordered stream where each element is
758      * generated by the provided {@code LongSupplier}.  This is suitable for
759      * generating constant streams, streams of random elements, etc.
760      *
761      * @param s the {@code LongSupplier} for generated elements
762      * @return a new infinite sequential unordered {@code LongStream}
763      */
generate(LongSupplier s)764     public static LongStream generate(LongSupplier s) {
765         Objects.requireNonNull(s);
766         return StreamSupport.longStream(
767                 new StreamSpliterators.InfiniteSupplyingSpliterator.OfLong(Long.MAX_VALUE, s), false);
768     }
769 
770     /**
771      * Returns a sequential ordered {@code LongStream} from {@code startInclusive}
772      * (inclusive) to {@code endExclusive} (exclusive) by an incremental step of
773      * {@code 1}.
774      *
775      * @apiNote
776      * <p>An equivalent sequence of increasing values can be produced
777      * sequentially using a {@code for} loop as follows:
778      * <pre>{@code
779      *     for (long i = startInclusive; i < endExclusive ; i++) { ... }
780      * }</pre>
781      *
782      * @param startInclusive the (inclusive) initial value
783      * @param endExclusive the exclusive upper bound
784      * @return a sequential {@code LongStream} for the range of {@code long}
785      *         elements
786      */
range(long startInclusive, final long endExclusive)787     public static LongStream range(long startInclusive, final long endExclusive) {
788         if (startInclusive >= endExclusive) {
789             return empty();
790         } else if (endExclusive - startInclusive < 0) {
791             // Size of range > Long.MAX_VALUE
792             // Split the range in two and concatenate
793             // Note: if the range is [Long.MIN_VALUE, Long.MAX_VALUE) then
794             // the lower range, [Long.MIN_VALUE, 0) will be further split in two
795             long m = startInclusive + Long.divideUnsigned(endExclusive - startInclusive, 2) + 1;
796             return concat(range(startInclusive, m), range(m, endExclusive));
797         } else {
798             return StreamSupport.longStream(
799                     new Streams.RangeLongSpliterator(startInclusive, endExclusive, false), false);
800         }
801     }
802 
803     /**
804      * Returns a sequential ordered {@code LongStream} 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 (long 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 LongStream} for the range of {@code long}
818      *         elements
819      */
rangeClosed(long startInclusive, final long endInclusive)820     public static LongStream rangeClosed(long startInclusive, final long endInclusive) {
821         if (startInclusive > endInclusive) {
822             return empty();
823         } else if (endInclusive - startInclusive + 1 <= 0) {
824             // Size of range > Long.MAX_VALUE
825             // Split the range in two and concatenate
826             // Note: if the range is [Long.MIN_VALUE, Long.MAX_VALUE] then
827             // the lower range, [Long.MIN_VALUE, 0), and upper range,
828             // [0, Long.MAX_VALUE], will both be further split in two
829             long m = startInclusive + Long.divideUnsigned(endInclusive - startInclusive, 2) + 1;
830             return concat(range(startInclusive, m), rangeClosed(m, endInclusive));
831         } else {
832             return StreamSupport.longStream(
833                     new Streams.RangeLongSpliterator(startInclusive, endInclusive, true), false);
834         }
835     }
836 
837     /**
838      * Creates a lazily concatenated stream whose elements are all the
839      * elements of the first stream followed by all the elements of the
840      * second stream.  The resulting stream is ordered if both
841      * of the input streams are ordered, and parallel if either of the input
842      * streams is parallel.  When the resulting stream is closed, the close
843      * handlers for both input streams are invoked.
844      *
845      * @implNote
846      * Use caution when constructing streams from repeated concatenation.
847      * Accessing an element of a deeply concatenated stream can result in deep
848      * call chains, or even {@code StackOverflowException}.
849      *
850      * @param a the first stream
851      * @param b the second stream
852      * @return the concatenation of the two input streams
853      */
concat(LongStream a, LongStream b)854     public static LongStream concat(LongStream a, LongStream b) {
855         Objects.requireNonNull(a);
856         Objects.requireNonNull(b);
857 
858         Spliterator.OfLong split = new Streams.ConcatSpliterator.OfLong(
859                 a.spliterator(), b.spliterator());
860         LongStream stream = StreamSupport.longStream(split, a.isParallel() || b.isParallel());
861         return stream.onClose(Streams.composedClose(a, b));
862     }
863 
864     /**
865      * A mutable builder for a {@code LongStream}.
866      *
867      * <p>A stream builder has a lifecycle, which starts in a building
868      * phase, during which elements can be added, and then transitions to a built
869      * phase, after which elements may not be added.  The built phase begins
870      * begins when the {@link #build()} method is called, which creates an
871      * ordered stream whose elements are the elements that were added to the
872      * stream builder, in the order they were added.
873      *
874      * @see LongStream#builder()
875      * @since 1.8
876      */
877     public interface Builder extends LongConsumer {
878 
879         /**
880          * Adds an element to the stream being built.
881          *
882          * @throws IllegalStateException if the builder has already transitioned
883          * to the built state
884          */
885         @Override
accept(long t)886         void accept(long t);
887 
888         /**
889          * Adds an element to the stream being built.
890          *
891          * @implSpec
892          * The default implementation behaves as if:
893          * <pre>{@code
894          *     accept(t)
895          *     return this;
896          * }</pre>
897          *
898          * @param t the element to add
899          * @return {@code this} builder
900          * @throws IllegalStateException if the builder has already transitioned
901          * to the built state
902          */
add(long t)903         default Builder add(long t) {
904             accept(t);
905             return this;
906         }
907 
908         /**
909          * Builds the stream, transitioning this builder to the built state.
910          * An {@code IllegalStateException} is thrown if there are further
911          * attempts to operate on the builder after it has entered the built
912          * state.
913          *
914          * @return the built stream
915          * @throws IllegalStateException if the builder has already transitioned
916          * to the built state
917          */
build()918         LongStream build();
919     }
920 }
921