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