1 /*
   2  * Copyright (c) 2012, 2013, Oracle and/or its affiliates. All rights reserved.
   3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
   4  *
   5  * This code is free software; you can redistribute it and/or modify it
   6  * under the terms of the GNU General Public License version 2 only, as
   7  * published by the Free Software Foundation.  Oracle designates this
   8  * particular file as subject to the "Classpath" exception as provided
   9  * by Oracle in the LICENSE file that accompanied this code.
  10  *
  11  * This code is distributed in the hope that it will be useful, but WITHOUT
  12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
  14  * version 2 for more details (a copy is included in the LICENSE file that
  15  * accompanied this code).
  16  *
  17  * You should have received a copy of the GNU General Public License version
  18  * 2 along with this work; if not, write to the Free Software Foundation,
  19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
  20  *
  21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
  22  * or visit www.oracle.com if you need additional information or have any
  23  * questions.
  24  */
  25 package java.util.stream;
  26 
  27 import java.nio.charset.Charset;
  28 import java.nio.file.Files;
  29 import java.nio.file.Path;
  30 import java.util.Arrays;
  31 import java.util.Collection;
  32 import java.util.DoubleSummaryStatistics;
  33 import java.util.Objects;
  34 import java.util.OptionalDouble;
  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.DoubleBinaryOperator;
  41 import java.util.function.DoubleConsumer;
  42 import java.util.function.DoubleFunction;
  43 import java.util.function.DoublePredicate;
  44 import java.util.function.DoubleSupplier;
  45 import java.util.function.DoubleToIntFunction;
  46 import java.util.function.DoubleToLongFunction;
  47 import java.util.function.DoubleUnaryOperator;
  48 import java.util.function.Function;
  49 import java.util.function.ObjDoubleConsumer;
  50 import java.util.function.Supplier;
  51 
  52 /**
  53  * A sequence of elements supporting sequential and parallel aggregate
  54  * operations.  The following example illustrates an aggregate operation using
  55  * {@link Stream} and {@link DoubleStream}:
  56  *
  57  * <pre>{@code
  58  *     double sum = widgets.stream()
  59  *                         .filter(w -> w.getColor() == RED)
  60  *                         .mapToDouble(w -> w.getWeight())
  61  *                         .sum();
  62  * }</pre>
  63  *
  64  * In this example, {@code widgets} is a {@code Collection<Widget>}.  We create
  65  * a stream of {@code Widget} objects via {@link Collection#stream Collection.stream()},
  66  * filter it to produce a stream containing only the red widgets, and then
  67  * transform it into a stream of {@code double} values representing the weight of
  68  * each red widget. Then this stream is summed to produce a total weight.
  69  *
  70  * <p>To perform a computation, stream
  71  * <a href="package-summary.html#StreamOps">operations</a> are composed into a
  72  * <em>stream pipeline</em>.  A stream pipeline consists of a source (which
  73  * might be an array, a collection, a generator function, an IO channel,
  74  * etc), zero or more <em>intermediate operations</em> (which transform a
  75  * stream into another stream, such as {@link DoubleStream#filter(DoublePredicate)}), and a
  76  * <em>terminal operation</em> (which produces a result or side-effect, such
  77  * as {@link DoubleStream#sum()} or {@link DoubleStream#forEach(DoubleConsumer)}.
  78  * Streams are lazy; computation on the source data is only performed when the
  79  * terminal operation is initiated, and source elements are consumed only
  80  * as needed.
  81  *
  82  * <p>Collections and streams, while bearing some superficial similarities,
  83  * have different goals.  Collections are primarily concerned with the efficient
  84  * management of, and access to, their elements.  By contrast, streams do not
  85  * provide a means to directly access or manipulate their elements, and are
  86  * instead concerned with declaratively describing their source and the
  87  * computational operations which will be performed in aggregate on that source.
  88  * However, if the provided stream operations do not offer the desired
  89  * functionality, the {@link #iterator()} and {@link #spliterator()} operations
  90  * can be used to perform a controlled traversal.
  91  *
  92  * <p>A stream pipeline, like the "widgets" example above, can be viewed as
  93  * a <em>query</em> on the stream source.  Unless the source was explicitly
  94  * designed for concurrent modification (such as a {@link ConcurrentHashMap}),
  95  * unpredictable or erroneous behavior may result from modifying the stream
  96  * source while it is being queried.
  97  *
  98  * <p>Most stream operations accept parameters that describe user-specified
  99  * behavior, such as the lambda expression {@code w -> w.getWeight()} passed to
 100  * {@code mapToDouble} in the example above.  Such parameters are always instances
 101  * of a <a href="../function/package-summary.html">functional interface</a> such
 102  * as {@link java.util.function.Function}, and are often lambda expressions or
 103  * method references.  These parameters can never be null, should not modify the
 104  * stream source, and should be
 105  * <a href="package-summary.html#NonInterference">effectively stateless</a>
 106  * (their result should not depend on any state that might change during
 107  * execution of the stream pipeline.)
 108  *
 109  * <p>A stream should be operated on (invoking an intermediate or terminal stream
 110  * operation) only once.  This rules out, for example, "forked" streams, where
 111  * the same source feeds two or more pipelines, or multiple traversals of the
 112  * same stream.  A stream implementation may throw {@link IllegalStateException}
 113  * if it detects that the stream is being reused. However, since some stream
 114  * operations may return their receiver rather than a new stream object, it may
 115  * not be possible to detect reuse in all cases.
 116  *
 117  * <p>Streams have a {@link #close()} method and implement {@link AutoCloseable},
 118  * but nearly all stream instances do not actually need to be closed after use.
 119  * Generally, only streams whose source is an IO channel (such as those returned
 120  * by {@link Files#lines(Path, Charset)}) will require closing.  Most streams
 121  * are backed by collections, arrays, or generating functions, which require no
 122  * special resource management.  (If a stream does require closing, it can be
 123  * declared as a resource in a {@code try}-with-resources statement.)
 124  *
 125  * <p>Stream pipelines may execute either sequentially or in
 126  * <a href="package-summary.html#Parallelism">parallel</a>.  This
 127  * execution mode is a property of the stream.  Streams are created
 128  * with an initial choice of sequential or parallel execution.  (For example,
 129  * {@link Collection#stream() Collection.stream()} creates a sequential stream,
 130  * and {@link Collection#parallelStream() Collection.parallelStream()} creates
 131  * a parallel one.)  This choice of execution mode may be modified by the
 132  * {@link #sequential()} or {@link #parallel()} methods, and may be queried with
 133  * the {@link #isParallel()} method.
 134  *
 135  * @since 1.8
 136  * @see <a href="package-summary.html">java.util.stream</a>
 137  */
 138 public interface DoubleStream extends BaseStream<Double, DoubleStream> {
 139 
 140     /**
 141      * Returns a stream consisting of the elements of this stream that match
 142      * the given predicate.
 143      *
 144      * <p>This is an <a href="package-summary.html#StreamOps">intermediate
 145      * operation</a>.
 146      *
 147      * @param predicate a <a href="package-summary.html#NonInterference">
 148      *                  non-interfering, stateless</a> predicate to apply to
 149      *                  each element to determine if it should be included
 150      * @return the new stream
 151      */
 152     DoubleStream filter(DoublePredicate predicate);
 153 
 154     /**
 155      * Returns a stream consisting of the results of applying the given
 156      * function to the elements of this stream.
 157      *
 158      * <p>This is an <a href="package-summary.html#StreamOps">intermediate
 159      * operation</a>.
 160      *
 161      * @param mapper a <a href="package-summary.html#NonInterference">
 162      *               non-interfering, stateless</a> function to apply to
 163      *               each element
 164      * @return the new stream
 165      */
 166     DoubleStream map(DoubleUnaryOperator mapper);
 167 
 168     /**
 169      * Returns an object-valued {@code Stream} consisting of the results of
 170      * applying the given function to the elements of this stream.
 171      *
 172      * <p>This is an <a href="package-summary.html#StreamOps">
 173      *     intermediate operation</a>.
 174      *
 175      * @param <U> the element type of the new stream
 176      * @param mapper a <a href="package-summary.html#NonInterference">
 177      *               non-interfering, stateless</a> function to apply to each
 178      *               element
 179      * @return the new stream
 180      */
 181     <U> Stream<U> mapToObj(DoubleFunction<? extends U> mapper);
 182 
 183     /**
 184      * Returns an {@code IntStream} consisting of the results of applying the
 185      * given function to the elements of this stream.
 186      *
 187      * <p>This is an <a href="package-summary.html#StreamOps">intermediate
 188      * operation</a>.
 189      *
 190      * @param mapper a <a href="package-summary.html#NonInterference">
 191      *               non-interfering, stateless</a> function to apply to each
 192      *               element
 193      * @return the new stream
 194      */
 195     IntStream mapToInt(DoubleToIntFunction mapper);
 196 
 197     /**
 198      * Returns a {@code LongStream} consisting of the results of applying the
 199      * given function to the elements of this stream.
 200      *
 201      * <p>This is an <a href="package-summary.html#StreamOps">intermediate
 202      * operation</a>.
 203      *
 204      * @param mapper a <a href="package-summary.html#NonInterference">
 205      *               non-interfering, stateless</a> function to apply to each
 206      *               element
 207      * @return the new stream
 208      */
 209     LongStream mapToLong(DoubleToLongFunction mapper);
 210 
 211     /**
 212      * Returns a stream consisting of the results of replacing each element of
 213      * this stream with the contents of the stream produced by applying the
 214      * provided mapping function to each element.  (If the result of the mapping
 215      * function is {@code null}, this is treated as if the result was an empty
 216      * stream.)
 217      *
 218      * <p>This is an <a href="package-summary.html#StreamOps">intermediate
 219      * operation</a>.
 220      *
 221      * @param mapper a <a href="package-summary.html#NonInterference">
 222      *               non-interfering, stateless</a> function to apply to
 223      *               each element which produces an {@code DoubleStream} of new
 224      *               values
 225      * @return the new stream
 226      * @see Stream#flatMap(Function)
 227      */
 228     DoubleStream flatMap(DoubleFunction<? extends DoubleStream> mapper);
 229 
 230     /**
 231      * Returns a stream consisting of the distinct elements of this stream. The
 232      * elements are compared for equality according to
 233      * {@link java.lang.Double#compare(double, double)}.
 234      *
 235      * <p>This is a <a href="package-summary.html#StreamOps">stateful
 236      * intermediate operation</a>.
 237      *
 238      * @return the result stream
 239      */
 240     DoubleStream distinct();
 241 
 242     /**
 243      * Returns a stream consisting of the elements of this stream in sorted
 244      * order. The elements are compared for equality according to
 245      * {@link java.lang.Double#compare(double, double)}.
 246      *
 247      * <p>This is a <a href="package-summary.html#StreamOps">stateful
 248      * intermediate operation</a>.
 249      *
 250      * @return the result stream
 251      */
 252     DoubleStream sorted();
 253 
 254     /**
 255      * Returns a stream consisting of the elements of this stream, additionally
 256      * performing the provided action on each element as elements are consumed
 257      * from the resulting stream.
 258      *
 259      * <p>This is an <a href="package-summary.html#StreamOps">intermediate
 260      * operation</a>.
 261      *
 262      * <p>For parallel stream pipelines, the action may be called at
 263      * whatever time and in whatever thread the element is made available by the
 264      * upstream operation.  If the action modifies shared state,
 265      * it is responsible for providing the required synchronization.
 266      *
 267      * @apiNote This method exists mainly to support debugging, where you want
 268      * to see the elements as they flow past a certain point in a pipeline:
 269      * <pre>{@code
 270      *     list.stream()
 271      *         .filter(filteringFunction)
 272      *         .peek(e -> System.out.println("Filtered value: " + e));
 273      *         .map(mappingFunction)
 274      *         .peek(e -> System.out.println("Mapped value: " + e));
 275      *         .collect(Collectors.toDoubleSummaryStastistics());
 276      * }</pre>
 277      *
 278      * @param action a <a href="package-summary.html#NonInterference">
 279      *                 non-interfering</a> action to perform on the elements as
 280      *                 they are consumed from the stream
 281      * @return the new stream
 282      */
 283     DoubleStream peek(DoubleConsumer action);
 284 
 285     /**
 286      * Returns a stream consisting of the elements of this stream, truncated
 287      * to be no longer than {@code maxSize} in length.
 288      *
 289      * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting
 290      * stateful intermediate operation</a>.
 291      *
 292      * @param maxSize the number of elements the stream should be limited to
 293      * @return the new stream
 294      * @throws IllegalArgumentException if {@code maxSize} is negative
 295      */
 296     DoubleStream limit(long maxSize);
 297 
 298     /**
 299      * Returns a stream consisting of the remaining elements of this stream
 300      * after discarding the first {@code startInclusive} elements of the stream.
 301      * If this stream contains fewer than {@code startInclusive} elements then an
 302      * empty stream will be returned.
 303      *
 304      * <p>This is a <a href="package-summary.html#StreamOps">stateful
 305      * intermediate operation</a>.
 306      *
 307      * @param startInclusive the number of leading elements to skip
 308      * @return the new stream
 309      * @throws IllegalArgumentException if {@code startInclusive} is negative
 310      */
 311     DoubleStream substream(long startInclusive);
 312 
 313     /**
 314      * Returns a stream consisting of the remaining elements of this stream
 315      * after discarding the first {@code startInclusive} elements and truncating
 316      * the result to be no longer than {@code endExclusive - startInclusive}
 317      * elements in length. If this stream contains fewer than
 318      * {@code startInclusive} elements then an empty stream will be returned.
 319      *
 320      * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting
 321      * stateful intermediate operation</a>.
 322      *
 323      * @param startInclusive the starting position of the substream, inclusive
 324      * @param endExclusive the ending position of the substream, exclusive
 325      * @return the new stream
 326      * @throws IllegalArgumentException if {@code startInclusive} or
 327      * {@code endExclusive} is negative or {@code startInclusive} is greater
 328      * than {@code endExclusive}
 329      */
 330     DoubleStream substream(long startInclusive, long endExclusive);
 331 
 332     /**
 333      * Performs an action for each element of this stream.
 334      *
 335      * <p>This is a <a href="package-summary.html#StreamOps">terminal
 336      * operation</a>.
 337      *
 338      * <p>For parallel stream pipelines, this operation does <em>not</em>
 339      * guarantee to respect the encounter order of the stream, as doing so
 340      * would sacrifice the benefit of parallelism.  For any given element, the
 341      * action may be performed at whatever time and in whatever thread the
 342      * library chooses.  If the action accesses shared state, it is
 343      * responsible for providing the required synchronization.
 344      *
 345      * @param action a <a href="package-summary.html#NonInterference">
 346      *               non-interfering</a> action to perform on the elements
 347      */
 348     void forEach(DoubleConsumer action);
 349 
 350     /**
 351      * Performs an action for each element of this stream, guaranteeing that
 352      * each element is processed in encounter order for streams that have a
 353      * defined encounter order.
 354      *
 355      * <p>This is a <a href="package-summary.html#StreamOps">terminal
 356      * operation</a>.
 357      *
 358      * @param action a <a href="package-summary.html#NonInterference">
 359      *               non-interfering</a> action to perform on the elements
 360      * @see #forEach(DoubleConsumer)
 361      */
 362     void forEachOrdered(DoubleConsumer action);
 363 
 364     /**
 365      * Returns an array containing the elements of this stream.
 366      *
 367      * <p>This is a <a href="package-summary.html#StreamOps">terminal
 368      * operation</a>.
 369      *
 370      * @return an array containing the elements of this stream
 371      */
 372     double[] toArray();
 373 
 374     /**
 375      * Performs a <a href="package-summary.html#Reduction">reduction</a> on the
 376      * elements of this stream, using the provided identity value and an
 377      * <a href="package-summary.html#Associativity">associative</a>
 378      * accumulation function, and returns the reduced value.  This is equivalent
 379      * to:
 380      * <pre>{@code
 381      *     double result = identity;
 382      *     for (double element : this stream)
 383      *         result = accumulator.apply(result, element)
 384      *     return result;
 385      * }</pre>
 386      *
 387      * but is not constrained to execute sequentially.
 388      *
 389      * <p>The {@code identity} value must be an identity for the accumulator
 390      * function. This means that for all {@code x},
 391      * {@code accumulator.apply(identity, x)} is equal to {@code x}.
 392      * The {@code accumulator} function must be an
 393      * <a href="package-summary.html#Associativity">associative</a> function.
 394      *
 395      * <p>This is a <a href="package-summary.html#StreamOps">terminal
 396      * operation</a>.
 397      *
 398      * @apiNote Sum, min, max, and average are all special cases of reduction.
 399      * Summing a stream of numbers can be expressed as:
 400 
 401      * <pre>{@code
 402      *     double sum = numbers.reduce(0, (a, b) -> a+b);
 403      * }</pre>
 404      *
 405      * or more compactly:
 406      *
 407      * <pre>{@code
 408      *     double sum = numbers.reduce(0, Double::sum);
 409      * }</pre>
 410      *
 411      * <p>While this may seem a more roundabout way to perform an aggregation
 412      * compared to simply mutating a running total in a loop, reduction
 413      * operations parallelize more gracefully, without needing additional
 414      * synchronization and with greatly reduced risk of data races.
 415      *
 416      * @param identity the identity value for the accumulating function
 417      * @param op an <a href="package-summary.html#Associativity">associative</a>
 418      *                    <a href="package-summary.html#NonInterference">non-interfering,
 419      *                    stateless</a> function for combining two values
 420      * @return the result of the reduction
 421      * @see #sum()
 422      * @see #min()
 423      * @see #max()
 424      * @see #average()
 425      */
 426     double reduce(double identity, DoubleBinaryOperator op);
 427 
 428     /**
 429      * Performs a <a href="package-summary.html#Reduction">reduction</a> on the
 430      * elements of this stream, using an
 431      * <a href="package-summary.html#Associativity">associative</a> accumulation
 432      * function, and returns an {@code OptionalDouble} describing the reduced
 433      * value, if any. This is equivalent to:
 434      * <pre>{@code
 435      *     boolean foundAny = false;
 436      *     double result = null;
 437      *     for (double element : this stream) {
 438      *         if (!foundAny) {
 439      *             foundAny = true;
 440      *             result = element;
 441      *         }
 442      *         else
 443      *             result = accumulator.apply(result, element);
 444      *     }
 445      *     return foundAny ? OptionalDouble.of(result) : OptionalDouble.empty();
 446      * }</pre>
 447      *
 448      * but is not constrained to execute sequentially.
 449      *
 450      * <p>The {@code accumulator} function must be an
 451      * <a href="package-summary.html#Associativity">associative</a> function.
 452      *
 453      * <p>This is a <a href="package-summary.html#StreamOps">terminal
 454      * operation</a>.
 455      *
 456      * @param op an <a href="package-summary.html#Associativity">associative</a>
 457      *           <a href="package-summary.html#NonInterference">non-interfering,
 458      *           stateless</a> function for combining two values
 459      * @return the result of the reduction
 460      * @see #reduce(double, DoubleBinaryOperator)
 461      */
 462     OptionalDouble reduce(DoubleBinaryOperator op);
 463 
 464     /**
 465      * Performs a <a href="package-summary.html#MutableReduction">mutable
 466      * reduction</a> operation on the elements of this stream.  A mutable
 467      * reduction is one in which the reduced value is a mutable result container,
 468      * such as an {@code ArrayList}, and elements are incorporated by updating
 469      * the state of the result rather than by replacing the result.  This
 470      * produces a result equivalent to:
 471      * <pre>{@code
 472      *     R result = supplier.get();
 473      *     for (double element : this stream)
 474      *         accumulator.accept(result, element);
 475      *     return result;
 476      * }</pre>
 477      *
 478      * <p>Like {@link #reduce(double, DoubleBinaryOperator)}, {@code collect}
 479      * operations can be parallelized without requiring additional
 480      * synchronization.
 481      *
 482      * <p>This is a <a href="package-summary.html#StreamOps">terminal
 483      * operation</a>.
 484      *
 485      * @param <R> type of the result
 486      * @param supplier a function that creates a new result container. For a
 487      *                 parallel execution, this function may be called
 488      *                 multiple times and must return a fresh value each time.
 489      * @param accumulator an <a href="package-summary.html#Associativity">associative</a>
 490      *                    <a href="package-summary.html#NonInterference">non-interfering,
 491      *                    stateless</a> function for incorporating an additional
 492      *                    element into a result
 493      * @param combiner an <a href="package-summary.html#Associativity">associative</a>
 494      *                 <a href="package-summary.html#NonInterference">non-interfering,
 495      *                 stateless</a> function for combining two values, which
 496      *                 must be compatible with the accumulator function
 497      * @return the result of the reduction
 498      * @see Stream#collect(Supplier, BiConsumer, BiConsumer)
 499      */
 500     <R> R collect(Supplier<R> supplier,
 501                   ObjDoubleConsumer<R> accumulator,
 502                   BiConsumer<R, R> combiner);
 503 
 504     /**
 505      * Returns the sum of elements in this stream.
 506      *
 507      * Summation is a special case of a <a
 508      * href="package-summary.html#Reduction">reduction</a>. If
 509      * floating-point summation were exact, this method would be
 510      * equivalent to:
 511      *
 512      * <pre>{@code
 513      *     return reduce(0, Double::sum);
 514      * }</pre>
 515      *
 516      * However, since floating-point summation is not exact, the above
 517      * code is not necessarily equivalent to the summation computation
 518      * done by this method.
 519      *
 520      * <p>If any stream element is a NaN or the sum is at any point a NaN
 521      * then the sum will be NaN.
 522      *
 523      * The value of a floating-point sum is a function both
 524      * of the input values as well as the order of addition
 525      * operations. The order of addition operations of this method is
 526      * intentionally not defined to allow for implementation
 527      * flexibility to improve the speed and accuracy of the computed
 528      * result.
 529      *
 530      * In particular, this method may be implemented using compensated
 531      * summation or other technique to reduce the error bound in the
 532      * numerical sum compared to a simple summation of {@code double}
 533      * values.
 534      *
 535      * <p>This is a <a href="package-summary.html#StreamOps">terminal
 536      * operation</a>.
 537      *
 538      * @apiNote Sorting values by increasing absolute magnitude tends to yield
 539      * more accurate results.
 540      *
 541      * @return the sum of elements in this stream
 542      */
 543     double sum();
 544 
 545     /**
 546      * Returns an {@code OptionalDouble} describing the minimum element of this
 547      * stream, or an empty OptionalDouble if this stream is empty.  The minimum
 548      * element will be {@code Double.NaN} if any stream element was NaN. Unlike
 549      * the numerical comparison operators, this method considers negative zero
 550      * to be strictly smaller than positive zero. This is a special case of a
 551      * <a href="package-summary.html#Reduction">reduction</a> and is
 552      * equivalent to:
 553      * <pre>{@code
 554      *     return reduce(Double::min);
 555      * }</pre>
 556      *
 557      * <p>This is a <a href="package-summary.html#StreamOps">terminal
 558      * operation</a>.
 559      *
 560      * @return an {@code OptionalDouble} containing the minimum element of this
 561      * stream, or an empty optional if the stream is empty
 562      */
 563     OptionalDouble min();
 564 
 565     /**
 566      * Returns an {@code OptionalDouble} describing the maximum element of this
 567      * stream, or an empty OptionalDouble if this stream is empty.  The maximum
 568      * element will be {@code Double.NaN} if any stream element was NaN. Unlike
 569      * the numerical comparison operators, this method considers negative zero
 570      * to be strictly smaller than positive zero. This is a
 571      * special case of a
 572      * <a href="package-summary.html#Reduction">reduction</a> and is
 573      * equivalent to:
 574      * <pre>{@code
 575      *     return reduce(Double::max);
 576      * }</pre>
 577      *
 578      * <p>This is a <a href="package-summary.html#StreamOps">terminal
 579      * operation</a>.
 580      *
 581      * @return an {@code OptionalDouble} containing the maximum element of this
 582      * stream, or an empty optional if the stream is empty
 583      */
 584     OptionalDouble max();
 585 
 586     /**
 587      * Returns the count of elements in this stream.  This is a special case of
 588      * a <a href="package-summary.html#Reduction">reduction</a> and is
 589      * equivalent to:
 590      * <pre>{@code
 591      *     return mapToLong(e -> 1L).sum();
 592      * }</pre>
 593      *
 594      * <p>This is a <a href="package-summary.html#StreamOps">terminal operation</a>.
 595      *
 596      * @return the count of elements in this stream
 597      */
 598     long count();
 599 
 600     /**
 601      * Returns an {@code OptionalDouble} describing the arithmetic
 602      * mean of elements of this stream, or an empty optional if this
 603      * stream is empty.
 604      *
 605      * If any recorded value is a NaN or the sum is at any point a NaN
 606      * then the average will be NaN.
 607      *
 608      * <p>The average returned can vary depending upon the order in
 609      * which values are recorded.
 610      *
 611      * This method may be implemented using compensated summation or
 612      * other technique to reduce the error bound in the {@link #sum
 613      * numerical sum} used to compute the average.
 614      *
 615      *  <p>The average is a special case of a <a
 616      *  href="package-summary.html#Reduction">reduction</a>.
 617      *
 618      * <p>This is a <a href="package-summary.html#StreamOps">terminal
 619      * operation</a>.
 620      *
 621      * @apiNote Elements sorted by increasing absolute magnitude tend
 622      * to yield more accurate results.
 623      *
 624      * @return an {@code OptionalDouble} containing the average element of this
 625      * stream, or an empty optional if the stream is empty
 626      */
 627     OptionalDouble average();
 628 
 629     /**
 630      * Returns a {@code DoubleSummaryStatistics} describing various summary data
 631      * about the elements of this stream.  This is a special
 632      * case of a <a href="package-summary.html#Reduction">reduction</a>.
 633      *
 634      * <p>This is a <a href="package-summary.html#StreamOps">terminal
 635      * operation</a>.
 636      *
 637      * @return a {@code DoubleSummaryStatistics} describing various summary data
 638      * about the elements of this stream
 639      */
 640     DoubleSummaryStatistics summaryStatistics();
 641 
 642     /**
 643      * Returns whether any elements of this stream match the provided
 644      * predicate.  May not evaluate the predicate on all elements if not
 645      * necessary for determining the result.
 646      *
 647      * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting
 648      * terminal operation</a>.
 649      *
 650      * @param predicate a <a href="package-summary.html#NonInterference">non-interfering,
 651      *                  stateless</a> predicate to apply to elements of this
 652      *                  stream
 653      * @return {@code true} if any elements of the stream match the provided
 654      * predicate otherwise {@code false}
 655      */
 656     boolean anyMatch(DoublePredicate predicate);
 657 
 658     /**
 659      * Returns whether all elements of this stream match the provided predicate.
 660      * May not evaluate the predicate on all elements if not necessary for
 661      * determining the result.
 662      *
 663      * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting
 664      * terminal operation</a>.
 665      *
 666      * @param predicate a <a href="package-summary.html#NonInterference">non-interfering,
 667      *                  stateless</a> predicate to apply to elements of this
 668      *                  stream
 669      * @return {@code true} if all elements of the stream match the provided
 670      * predicate otherwise {@code false}
 671      */
 672     boolean allMatch(DoublePredicate predicate);
 673 
 674     /**
 675      * Returns whether no elements of this stream match the provided predicate.
 676      * May not evaluate the predicate on all elements if not necessary for
 677      * determining the result.
 678      *
 679      * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting
 680      * terminal operation</a>.
 681      *
 682      * @param predicate a <a href="package-summary.html#NonInterference">non-interfering,
 683      *                  stateless</a> predicate to apply to elements of this
 684      *                  stream
 685      * @return {@code true} if no elements of the stream match the provided
 686      * predicate otherwise {@code false}
 687      */
 688     boolean noneMatch(DoublePredicate predicate);
 689 
 690     /**
 691      * Returns an {@link OptionalDouble} describing the first element of this
 692      * stream, or an empty {@code OptionalDouble} if the stream is empty.  If
 693      * the stream has no encounter order, then any element may be returned.
 694      *
 695      * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting
 696      * terminal operation</a>.
 697      *
 698      * @return an {@code OptionalDouble} describing the first element of this
 699      * stream, or an empty {@code OptionalDouble} if the stream is empty
 700      */
 701     OptionalDouble findFirst();
 702 
 703     /**
 704      * Returns an {@link OptionalDouble} describing some element of the stream,
 705      * or an empty {@code OptionalDouble} if the stream is empty.
 706      *
 707      * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting
 708      * terminal operation</a>.
 709      *
 710      * <p>The behavior of this operation is explicitly nondeterministic; it is
 711      * free to select any element in the stream.  This is to allow for maximal
 712      * performance in parallel operations; the cost is that multiple invocations
 713      * on the same source may not return the same result.  (If a stable result
 714      * is desired, use {@link #findFirst()} instead.)
 715      *
 716      * @return an {@code OptionalDouble} describing some element of this stream,
 717      * or an empty {@code OptionalDouble} if the stream is empty
 718      * @see #findFirst()
 719      */
 720     OptionalDouble findAny();
 721 
 722     /**
 723      * Returns a {@code Stream} consisting of the elements of this stream,
 724      * boxed to {@code Double}.
 725      *
 726      * <p>This is an <a href="package-summary.html#StreamOps">intermediate
 727      * operation</a>.
 728      *
 729      * @return a {@code Stream} consistent of the elements of this stream,
 730      * each boxed to a {@code Double}
 731      */
 732     Stream<Double> boxed();
 733 
 734     @Override
 735     DoubleStream sequential();
 736 
 737     @Override
 738     DoubleStream parallel();
 739 
 740     @Override
 741     PrimitiveIterator.OfDouble iterator();
 742 
 743     @Override
 744     Spliterator.OfDouble spliterator();
 745 
 746 
 747     // Static factories
 748 
 749     /**
 750      * Returns a builder for a {@code DoubleStream}.
 751      *
 752      * @return a stream builder
 753      */
 754     public static Builder builder() {
 755         return new Streams.DoubleStreamBuilderImpl();
 756     }
 757 
 758     /**
 759      * Returns an empty sequential {@code DoubleStream}.
 760      *
 761      * @return an empty sequential stream
 762      */
 763     public static DoubleStream empty() {
 764         return StreamSupport.doubleStream(Spliterators.emptyDoubleSpliterator(), false);
 765     }
 766 
 767     /**
 768      * Returns a sequential {@code DoubleStream} containing a single element.
 769      *
 770      * @param t the single element
 771      * @return a singleton sequential stream
 772      */
 773     public static DoubleStream of(double t) {
 774         return StreamSupport.doubleStream(new Streams.DoubleStreamBuilderImpl(t), false);
 775     }
 776 
 777     /**
 778      * Returns a sequential ordered stream whose elements are the specified values.
 779      *
 780      * @param values the elements of the new stream
 781      * @return the new stream
 782      */
 783     public static DoubleStream of(double... values) {
 784         return Arrays.stream(values);
 785     }
 786 
 787     /**
 788      * Returns an infinite sequential ordered {@code DoubleStream} produced by iterative
 789      * application of a function {@code f} to an initial element {@code seed},
 790      * producing a {@code Stream} consisting of {@code seed}, {@code f(seed)},
 791      * {@code f(f(seed))}, etc.
 792      *
 793      * <p>The first element (position {@code 0}) in the {@code DoubleStream}
 794      * will be the provided {@code seed}.  For {@code n > 0}, the element at
 795      * position {@code n}, will be the result of applying the function {@code f}
 796      *  to the element at position {@code n - 1}.
 797      *
 798      * @param seed the initial element
 799      * @param f a function to be applied to to the previous element to produce
 800      *          a new element
 801      * @return a new sequential {@code DoubleStream}
 802      */
 803     public static DoubleStream iterate(final double seed, final DoubleUnaryOperator f) {
 804         Objects.requireNonNull(f);
 805         final PrimitiveIterator.OfDouble iterator = new PrimitiveIterator.OfDouble() {
 806             double t = seed;
 807 
 808             @Override
 809             public boolean hasNext() {
 810                 return true;
 811             }
 812 
 813             @Override
 814             public double nextDouble() {
 815                 double v = t;
 816                 t = f.applyAsDouble(t);
 817                 return v;
 818             }
 819         };
 820         return StreamSupport.doubleStream(Spliterators.spliteratorUnknownSize(
 821                 iterator,
 822                 Spliterator.ORDERED | Spliterator.IMMUTABLE | Spliterator.NONNULL), false);
 823     }
 824 
 825     /**
 826      * Returns a sequential stream where each element is generated by
 827      * the provided {@code DoubleSupplier}.  This is suitable for generating
 828      * constant streams, streams of random elements, etc.
 829      *
 830      * @param s the {@code DoubleSupplier} for generated elements
 831      * @return a new sequential {@code DoubleStream}
 832      */
 833     public static DoubleStream generate(DoubleSupplier s) {
 834         Objects.requireNonNull(s);
 835         return StreamSupport.doubleStream(
 836                 new StreamSpliterators.InfiniteSupplyingSpliterator.OfDouble(Long.MAX_VALUE, s), false);
 837     }
 838 
 839     /**
 840      * Creates a lazily concatenated stream whose elements are all the
 841      * elements of the first stream followed by all the elements of the
 842      * second stream. The resulting stream is ordered if both
 843      * of the input streams are ordered, and parallel if either of the input
 844      * streams is parallel.  When the resulting stream is closed, the close
 845      * handlers for both input streams are invoked.
 846      *
 847      * @param a the first stream
 848      * @param b the second stream
 849      * @return the concatenation of the two input streams
 850      */
 851     public static DoubleStream concat(DoubleStream a, DoubleStream b) {
 852         Objects.requireNonNull(a);
 853         Objects.requireNonNull(b);
 854 
 855         Spliterator.OfDouble split = new Streams.ConcatSpliterator.OfDouble(
 856                 a.spliterator(), b.spliterator());
 857         DoubleStream stream = StreamSupport.doubleStream(split, a.isParallel() || b.isParallel());
 858         return stream.onClose(Streams.composedClose(a, b));
 859     }
 860 
 861     /**
 862      * A mutable builder for a {@code DoubleStream}.
 863      *
 864      * <p>A stream builder has a lifecycle, which starts in a building
 865      * phase, during which elements can be added, and then transitions to a built
 866      * phase, after which elements may not be added.  The built phase
 867      * begins when the {@link #build()} method is called, which creates an
 868      * ordered stream whose elements are the elements that were added to the
 869      * stream builder, in the order they were added.
 870      *
 871      * @see DoubleStream#builder()
 872      * @since 1.8
 873      */
 874     public interface Builder extends DoubleConsumer {
 875 
 876         /**
 877          * Adds an element to the stream being built.
 878          *
 879          * @throws IllegalStateException if the builder has already transitioned
 880          * to the built state
 881          */
 882         @Override
 883         void accept(double t);
 884 
 885         /**
 886          * Adds an element to the stream being built.
 887          *
 888          * @implSpec
 889          * The default implementation behaves as if:
 890          * <pre>{@code
 891          *     accept(t)
 892          *     return this;
 893          * }</pre>
 894          *
 895          * @param t the element to add
 896          * @return {@code this} builder
 897          * @throws IllegalStateException if the builder has already transitioned
 898          * to the built state
 899          */
 900         default Builder add(double t) {
 901             accept(t);
 902             return this;
 903         }
 904 
 905         /**
 906          * Builds the stream, transitioning this builder to the built state.
 907          * An {@code IllegalStateException} is thrown if there are further
 908          * attempts to operate on the builder after it has entered the built
 909          * state.
 910          *
 911          * @return the built stream
 912          * @throws IllegalStateException if the builder has already transitioned
 913          * to the built state
 914          */
 915         DoubleStream build();
 916     }
 917 }