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


 976     }
 977 
 978     /**
 979      * Returns an infinite sequential unordered stream where each element is
 980      * generated by the provided {@code LongSupplier}.  This is suitable for
 981      * generating constant streams, streams of random elements, etc.
 982      *
 983      * @param s the {@code LongSupplier} for generated elements
 984      * @return a new infinite sequential unordered {@code LongStream}
 985      */
 986     public static LongStream generate(LongSupplier s) {
 987         Objects.requireNonNull(s);
 988         return StreamSupport.longStream(
 989                 new StreamSpliterators.InfiniteSupplyingSpliterator.OfLong(Long.MAX_VALUE, s), false);
 990     }
 991 
 992     /**
 993      * Returns a sequential ordered {@code LongStream} from {@code startInclusive}
 994      * (inclusive) to {@code endExclusive} (exclusive) by an incremental step of
 995      * {@code 1}.
 996      *
 997      * @apiNote
 998      * <p>An equivalent sequence of increasing values can be produced
 999      * sequentially using a {@code for} loop as follows:
1000      * <pre>{@code
1001      *     for (long i = startInclusive; i < endExclusive ; i++) { ... }
1002      * }</pre>
1003      *
1004      * @param startInclusive the (inclusive) initial value
1005      * @param endExclusive the exclusive upper bound
1006      * @return a sequential {@code LongStream} for the range of {@code long}
1007      *         elements
1008      */
1009     public static LongStream range(long startInclusive, final long endExclusive) {
1010         if (startInclusive >= endExclusive) {
1011             return empty();
1012         } else if (endExclusive - startInclusive < 0) {
1013             // Size of range > Long.MAX_VALUE
1014             // Split the range in two and concatenate
1015             // Note: if the range is [Long.MIN_VALUE, Long.MAX_VALUE) then
1016             // the lower range, [Long.MIN_VALUE, 0) will be further split in two
1017             long m = startInclusive + Long.divideUnsigned(endExclusive - startInclusive, 2) + 1;
1018             return concat(range(startInclusive, m), range(m, endExclusive));
1019         } else {
1020             return StreamSupport.longStream(
1021                     new Streams.RangeLongSpliterator(startInclusive, endExclusive, false), false);
1022         }
1023     }
1024 
1025     /**
1026      * Returns a sequential ordered {@code LongStream} from {@code startInclusive}
1027      * (inclusive) to {@code endInclusive} (inclusive) by an incremental step of
1028      * {@code 1}.
1029      *
1030      * @apiNote
1031      * <p>An equivalent sequence of increasing values can be produced
1032      * sequentially using a {@code for} loop as follows:
1033      * <pre>{@code
1034      *     for (long i = startInclusive; i <= endInclusive ; i++) { ... }
1035      * }</pre>
1036      *
1037      * @param startInclusive the (inclusive) initial value
1038      * @param endInclusive the inclusive upper bound
1039      * @return a sequential {@code LongStream} for the range of {@code long}
1040      *         elements
1041      */
1042     public static LongStream rangeClosed(long startInclusive, final long endInclusive) {
1043         if (startInclusive > endInclusive) {
1044             return empty();
1045         } else if (endInclusive - startInclusive + 1 <= 0) {
1046             // Size of range > Long.MAX_VALUE
1047             // Split the range in two and concatenate
1048             // Note: if the range is [Long.MIN_VALUE, Long.MAX_VALUE] then
1049             // the lower range, [Long.MIN_VALUE, 0), and upper range,
1050             // [0, Long.MAX_VALUE], will both be further split in two
1051             long m = startInclusive + Long.divideUnsigned(endInclusive - startInclusive, 2) + 1;
1052             return concat(range(startInclusive, m), rangeClosed(m, endInclusive));
1053         } else {
1054             return StreamSupport.longStream(
1055                     new Streams.RangeLongSpliterator(startInclusive, endInclusive, true), false);
1056         }
1057     }
1058 
1059     /**
1060      * Creates a lazily concatenated stream whose elements are all the
1061      * elements of the first stream followed by all the elements of the
1062      * second stream.  The resulting stream is ordered if both
1063      * of the input streams are ordered, and parallel if either of the input
1064      * streams is parallel.  When the resulting stream is closed, the close
1065      * handlers for both input streams are invoked.
1066      *
1067      * @implNote
1068      * Use caution when constructing streams from repeated concatenation.
1069      * Accessing an element of a deeply concatenated stream can result in deep
1070      * call chains, or even {@code StackOverflowError}.
1071      *
1072      * @param a the first stream
1073      * @param b the second stream
1074      * @return the concatenation of the two input streams
1075      */
1076     public static LongStream concat(LongStream a, LongStream b) {
1077         Objects.requireNonNull(a);
1078         Objects.requireNonNull(b);
1079 
1080         Spliterator.OfLong split = new Streams.ConcatSpliterator.OfLong(
1081                 a.spliterator(), b.spliterator());
1082         LongStream stream = StreamSupport.longStream(split, a.isParallel() || b.isParallel());
1083         return stream.onClose(Streams.composedClose(a, b));
1084     }
1085 
1086     /**
1087      * A mutable builder for a {@code LongStream}.
1088      *
1089      * <p>A stream builder has a lifecycle, which starts in a building
1090      * phase, during which elements can be added, and then transitions to a built
1091      * phase, after which elements may not be added.  The built phase begins
1092      * begins when the {@link #build()} method is called, which creates an
1093      * ordered stream whose elements are the elements that were added to the
1094      * stream builder, in the order they were added.
1095      *
1096      * @see LongStream#builder()
1097      * @since 1.8
1098      */
1099     public interface Builder extends LongConsumer {
1100 
1101         /**
1102          * Adds an element to the stream being built.
1103          *
1104          * @throws IllegalStateException if the builder has already transitioned
1105          * to the built state
1106          */
1107         @Override
1108         void accept(long t);
1109 
1110         /**
1111          * Adds an element to the stream being built.
1112          *
1113          * @implSpec
1114          * The default implementation behaves as if:
1115          * <pre>{@code
1116          *     accept(t)
1117          *     return this;
1118          * }</pre>
1119          *
1120          * @param t the element to add
1121          * @return {@code this} builder
1122          * @throws IllegalStateException if the builder has already transitioned
1123          * to the built state
1124          */
1125         default Builder add(long t) {
1126             accept(t);
1127             return this;
1128         }
1129 
1130         /**
1131          * Builds the stream, transitioning this builder to the built state.
1132          * An {@code IllegalStateException} is thrown if there are further
1133          * attempts to operate on the builder after it has entered the built
1134          * state.
1135          *
1136          * @return the built stream
1137          * @throws IllegalStateException if the builder has already transitioned
1138          * to the built state
1139          */
1140         LongStream build();
1141     }
1142 }
--- EOF ---