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