1/*
2 * Copyright (c) 2012, 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 */
25package java.util.stream;
26
27import java.util.Arrays;
28import java.util.DoubleSummaryStatistics;
29import java.util.Objects;
30import java.util.OptionalDouble;
31import java.util.PrimitiveIterator;
32import java.util.Spliterator;
33import java.util.Spliterators;
34import java.util.function.BiConsumer;
35import java.util.function.DoubleBinaryOperator;
36import java.util.function.DoubleConsumer;
37import java.util.function.DoubleFunction;
38import java.util.function.DoublePredicate;
39import java.util.function.DoubleSupplier;
40import java.util.function.DoubleToIntFunction;
41import java.util.function.DoubleToLongFunction;
42import java.util.function.DoubleUnaryOperator;
43import java.util.function.Function;
44import java.util.function.ObjDoubleConsumer;
45import java.util.function.Supplier;
46
47/**
48 * A sequence of primitive double-valued elements supporting sequential and parallel
49 * aggregate operations.  This is the {@code double} primitive specialization of
50 * {@link Stream}.
51 *
52 * <p>The following example illustrates an aggregate operation using
53 * {@link Stream} and {@link DoubleStream}, computing the sum of the weights of the
54 * red widgets:
55 *
56 * <pre>{@code
57 *     double sum = widgets.stream()
58 *                         .filter(w -> w.getColor() == RED)
59 *                         .mapToDouble(w -> w.getWeight())
60 *                         .sum();
61 * }</pre>
62 *
63 * See the class documentation for {@link Stream} and the package documentation
64 * for <a href="package-summary.html">java.util.stream</a> for additional
65 * specification of streams, stream operations, stream pipelines, and
66 * parallelism.
67 *
68 * @since 1.8
69 * @see Stream
70 * @see <a href="package-summary.html">java.util.stream</a>
71 */
72public interface DoubleStream extends BaseStream<Double, DoubleStream> {
73
74    /**
75     * Returns a stream consisting of the elements of this stream that match
76     * the given predicate.
77     *
78     * <p>This is an <a href="package-summary.html#StreamOps">intermediate
79     * operation</a>.
80     *
81     * @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>,
82     *                  <a href="package-summary.html#Statelessness">stateless</a>
83     *                  predicate to apply to each element to determine if it
84     *                  should be included
85     * @return the new stream
86     */
87    DoubleStream filter(DoublePredicate predicate);
88
89    /**
90     * Returns a stream consisting of the results of applying the given
91     * function to the elements of this stream.
92     *
93     * <p>This is an <a href="package-summary.html#StreamOps">intermediate
94     * operation</a>.
95     *
96     * @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>,
97     *               <a href="package-summary.html#Statelessness">stateless</a>
98     *               function to apply to each element
99     * @return the new stream
100     */
101    DoubleStream map(DoubleUnaryOperator mapper);
102
103    /**
104     * Returns an object-valued {@code Stream} consisting of the results of
105     * applying the given function to the elements of this stream.
106     *
107     * <p>This is an <a href="package-summary.html#StreamOps">
108     *     intermediate operation</a>.
109     *
110     * @param <U> the element type of the new stream
111     * @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>,
112     *               <a href="package-summary.html#Statelessness">stateless</a>
113     *               function to apply to each element
114     * @return the new stream
115     */
116    <U> Stream<U> mapToObj(DoubleFunction<? extends U> mapper);
117
118    /**
119     * Returns an {@code IntStream} consisting of the results of applying the
120     * given function to the elements of this stream.
121     *
122     * <p>This is an <a href="package-summary.html#StreamOps">intermediate
123     * operation</a>.
124     *
125     * @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>,
126     *               <a href="package-summary.html#Statelessness">stateless</a>
127     *               function to apply to each element
128     * @return the new stream
129     */
130    IntStream mapToInt(DoubleToIntFunction mapper);
131
132    /**
133     * Returns a {@code LongStream} consisting of the results of applying the
134     * given function to the elements of this stream.
135     *
136     * <p>This is an <a href="package-summary.html#StreamOps">intermediate
137     * operation</a>.
138     *
139     * @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>,
140     *               <a href="package-summary.html#Statelessness">stateless</a>
141     *               function to apply to each element
142     * @return the new stream
143     */
144    LongStream mapToLong(DoubleToLongFunction mapper);
145
146    /**
147     * Returns a stream consisting of the results of replacing each element of
148     * this stream with the contents of a mapped stream produced by applying
149     * the provided mapping function to each element.  Each mapped stream is
150     * {@link java.util.stream.BaseStream#close() closed} after its contents
151     * have been placed into this stream.  (If a mapped stream is {@code null}
152     * an empty stream is used, instead.)
153     *
154     * <p>This is an <a href="package-summary.html#StreamOps">intermediate
155     * operation</a>.
156     *
157     * @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>,
158     *               <a href="package-summary.html#Statelessness">stateless</a>
159     *               function to apply to each element which produces a
160     *               {@code DoubleStream} of new values
161     * @return the new stream
162     * @see Stream#flatMap(Function)
163     */
164    DoubleStream flatMap(DoubleFunction<? extends DoubleStream> mapper);
165
166    /**
167     * Returns a stream consisting of the distinct elements of this stream. The
168     * elements are compared for equality according to
169     * {@link java.lang.Double#compare(double, double)}.
170     *
171     * <p>This is a <a href="package-summary.html#StreamOps">stateful
172     * intermediate operation</a>.
173     *
174     * @return the result stream
175     */
176    DoubleStream distinct();
177
178    /**
179     * Returns a stream consisting of the elements of this stream in sorted
180     * order. The elements are compared for equality according to
181     * {@link java.lang.Double#compare(double, double)}.
182     *
183     * <p>This is a <a href="package-summary.html#StreamOps">stateful
184     * intermediate operation</a>.
185     *
186     * @return the result stream
187     */
188    DoubleStream sorted();
189
190    /**
191     * Returns a stream consisting of the elements of this stream, additionally
192     * performing the provided action on each element as elements are consumed
193     * from the resulting stream.
194     *
195     * <p>This is an <a href="package-summary.html#StreamOps">intermediate
196     * operation</a>.
197     *
198     * <p>For parallel stream pipelines, the action may be called at
199     * whatever time and in whatever thread the element is made available by the
200     * upstream operation.  If the action modifies shared state,
201     * it is responsible for providing the required synchronization.
202     *
203     * @apiNote This method exists mainly to support debugging, where you want
204     * to see the elements as they flow past a certain point in a pipeline:
205     * <pre>{@code
206     *     DoubleStream.of(1, 2, 3, 4)
207     *         .filter(e -> e > 2)
208     *         .peek(e -> System.out.println("Filtered value: " + e))
209     *         .map(e -> e * e)
210     *         .peek(e -> System.out.println("Mapped value: " + e))
211     *         .sum();
212     * }</pre>
213     *
214     * <p>In cases where the stream implementation is able to optimize away the
215     * production of some or all the elements (such as with short-circuiting
216     * operations like {@code findFirst}, or in the example described in
217     * {@link #count}), the action will not be invoked for those elements.
218     *
219     * @param action a <a href="package-summary.html#NonInterference">
220     *               non-interfering</a> action to perform on the elements as
221     *               they are consumed from the stream
222     * @return the new stream
223     */
224    DoubleStream peek(DoubleConsumer action);
225
226    /**
227     * Returns a stream consisting of the elements of this stream, truncated
228     * to be no longer than {@code maxSize} in length.
229     *
230     * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting
231     * stateful intermediate operation</a>.
232     *
233     * @apiNote
234     * While {@code limit()} is generally a cheap operation on sequential
235     * stream pipelines, it can be quite expensive on ordered parallel pipelines,
236     * especially for large values of {@code maxSize}, since {@code limit(n)}
237     * is constrained to return not just any <em>n</em> elements, but the
238     * <em>first n</em> elements in the encounter order.  Using an unordered
239     * stream source (such as {@link #generate(DoubleSupplier)}) or removing the
240     * ordering constraint with {@link #unordered()} may result in significant
241     * speedups of {@code limit()} in parallel pipelines, if the semantics of
242     * your situation permit.  If consistency with encounter order is required,
243     * and you are experiencing poor performance or memory utilization with
244     * {@code limit()} in parallel pipelines, switching to sequential execution
245     * with {@link #sequential()} may improve performance.
246     *
247     * @param maxSize the number of elements the stream should be limited to
248     * @return the new stream
249     * @throws IllegalArgumentException if {@code maxSize} is negative
250     */
251    DoubleStream limit(long maxSize);
252
253    /**
254     * Returns a stream consisting of the remaining elements of this stream
255     * after discarding the first {@code n} elements of the stream.
256     * If this stream contains fewer than {@code n} elements then an
257     * empty stream will be returned.
258     *
259     * <p>This is a <a href="package-summary.html#StreamOps">stateful
260     * intermediate operation</a>.
261     *
262     * @apiNote
263     * While {@code skip()} is generally a cheap operation on sequential
264     * stream pipelines, it can be quite expensive on ordered parallel pipelines,
265     * especially for large values of {@code n}, since {@code skip(n)}
266     * is constrained to skip not just any <em>n</em> elements, but the
267     * <em>first n</em> elements in the encounter order.  Using an unordered
268     * stream source (such as {@link #generate(DoubleSupplier)}) or removing the
269     * ordering constraint with {@link #unordered()} may result in significant
270     * speedups of {@code skip()} in parallel pipelines, if the semantics of
271     * your situation permit.  If consistency with encounter order is required,
272     * and you are experiencing poor performance or memory utilization with
273     * {@code skip()} in parallel pipelines, switching to sequential execution
274     * with {@link #sequential()} may improve performance.
275     *
276     * @param n the number of leading elements to skip
277     * @return the new stream
278     * @throws IllegalArgumentException if {@code n} is negative
279     */
280    DoubleStream skip(long n);
281
282    /**
283     * Returns, if this stream is ordered, a stream consisting of the longest
284     * prefix of elements taken from this stream that match the given predicate.
285     * Otherwise returns, if this stream is unordered, a stream consisting of a
286     * subset of elements taken from this stream that match the given predicate.
287     *
288     * <p>If this stream is ordered then the longest prefix is a contiguous
289     * sequence of elements of this stream that match the given predicate.  The
290     * first element of the sequence is the first element of this stream, and
291     * the element immediately following the last element of the sequence does
292     * not match the given predicate.
293     *
294     * <p>If this stream is unordered, and some (but not all) elements of this
295     * stream match the given predicate, then the behavior of this operation is
296     * nondeterministic; it is free to take any subset of matching elements
297     * (which includes the empty set).
298     *
299     * <p>Independent of whether this stream is ordered or unordered if all
300     * elements of this stream match the given predicate then this operation
301     * takes all elements (the result is the same as the input), or if no
302     * elements of the stream match the given predicate then no elements are
303     * taken (the result is an empty stream).
304     *
305     * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting
306     * stateful intermediate operation</a>.
307     *
308     * @implSpec
309     * The default implementation obtains the {@link #spliterator() spliterator}
310     * of this stream, wraps that spliterator so as to support the semantics
311     * of this operation on traversal, and returns a new stream associated with
312     * the wrapped spliterator.  The returned stream preserves the execution
313     * characteristics of this stream (namely parallel or sequential execution
314     * as per {@link #isParallel()}) but the wrapped spliterator may choose to
315     * not support splitting.  When the returned stream is closed, the close
316     * handlers for both the returned and this stream are invoked.
317     *
318     * @apiNote
319     * While {@code takeWhile()} is generally a cheap operation on sequential
320     * stream pipelines, it can be quite expensive on ordered parallel
321     * pipelines, since the operation is constrained to return not just any
322     * valid prefix, but the longest prefix of elements in the encounter order.
323     * Using an unordered stream source (such as
324     * {@link #generate(DoubleSupplier)}) or removing the ordering constraint
325     * with {@link #unordered()} may result in significant speedups of
326     * {@code takeWhile()} in parallel pipelines, if the semantics of your
327     * situation permit.  If consistency with encounter order is required, and
328     * you are experiencing poor performance or memory utilization with
329     * {@code takeWhile()} in parallel pipelines, switching to sequential
330     * execution with {@link #sequential()} may improve performance.
331     *
332     * @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>,
333     *                  <a href="package-summary.html#Statelessness">stateless</a>
334     *                  predicate to apply to elements to determine the longest
335     *                  prefix of elements.
336     * @return the new stream
337     * @since 9
338     */
339    default DoubleStream takeWhile(DoublePredicate predicate) {
340        Objects.requireNonNull(predicate);
341        // Reuses the unordered spliterator, which, when encounter is present,
342        // is safe to use as long as it configured not to split
343        return StreamSupport.doubleStream(
344                new WhileOps.UnorderedWhileSpliterator.OfDouble.Taking(spliterator(), true, predicate),
345                isParallel()).onClose(this::close);
346    }
347
348    /**
349     * Returns, if this stream is ordered, a stream consisting of the remaining
350     * elements of this stream after dropping the longest prefix of elements
351     * that match the given predicate.  Otherwise returns, if this stream is
352     * unordered, a stream consisting of the remaining elements of this stream
353     * after dropping a subset of elements that match the given predicate.
354     *
355     * <p>If this stream is ordered then the longest prefix is a contiguous
356     * sequence of elements of this stream that match the given predicate.  The
357     * first element of the sequence is the first element of this stream, and
358     * the element immediately following the last element of the sequence does
359     * not match the given predicate.
360     *
361     * <p>If this stream is unordered, and some (but not all) elements of this
362     * stream match the given predicate, then the behavior of this operation is
363     * nondeterministic; it is free to drop any subset of matching elements
364     * (which includes the empty set).
365     *
366     * <p>Independent of whether this stream is ordered or unordered if all
367     * elements of this stream match the given predicate then this operation
368     * drops all elements (the result is an empty stream), or if no elements of
369     * the stream match the given predicate then no elements are dropped (the
370     * result is the same as the input).
371     *
372     * <p>This is a <a href="package-summary.html#StreamOps">stateful
373     * intermediate operation</a>.
374     *
375     * @implSpec
376     * The default implementation obtains the {@link #spliterator() spliterator}
377     * of this stream, wraps that spliterator so as to support the semantics
378     * of this operation on traversal, and returns a new stream associated with
379     * the wrapped spliterator.  The returned stream preserves the execution
380     * characteristics of this stream (namely parallel or sequential execution
381     * as per {@link #isParallel()}) but the wrapped spliterator may choose to
382     * not support splitting.  When the returned stream is closed, the close
383     * handlers for both the returned and this stream are invoked.
384     *
385     * @apiNote
386     * While {@code dropWhile()} is generally a cheap operation on sequential
387     * stream pipelines, it can be quite expensive on ordered parallel
388     * pipelines, since the operation is constrained to return not just any
389     * valid prefix, but the longest prefix of elements in the encounter order.
390     * Using an unordered stream source (such as
391     * {@link #generate(DoubleSupplier)}) or removing the ordering constraint
392     * with {@link #unordered()} may result in significant speedups of
393     * {@code dropWhile()} in parallel pipelines, if the semantics of your
394     * situation permit.  If consistency with encounter order is required, and
395     * you are experiencing poor performance or memory utilization with
396     * {@code dropWhile()} in parallel pipelines, switching to sequential
397     * execution with {@link #sequential()} may improve performance.
398     *
399     * @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>,
400     *                  <a href="package-summary.html#Statelessness">stateless</a>
401     *                  predicate to apply to elements to determine the longest
402     *                  prefix of elements.
403     * @return the new stream
404     * @since 9
405     */
406    default DoubleStream dropWhile(DoublePredicate predicate) {
407        Objects.requireNonNull(predicate);
408        // Reuses the unordered spliterator, which, when encounter is present,
409        // is safe to use as long as it configured not to split
410        return StreamSupport.doubleStream(
411                new WhileOps.UnorderedWhileSpliterator.OfDouble.Dropping(spliterator(), true, predicate),
412                isParallel()).onClose(this::close);
413    }
414
415    /**
416     * Performs an action for each element of this stream.
417     *
418     * <p>This is a <a href="package-summary.html#StreamOps">terminal
419     * operation</a>.
420     *
421     * <p>For parallel stream pipelines, this operation does <em>not</em>
422     * guarantee to respect the encounter order of the stream, as doing so
423     * would sacrifice the benefit of parallelism.  For any given element, the
424     * action may be performed at whatever time and in whatever thread the
425     * library chooses.  If the action accesses shared state, it is
426     * responsible for providing the required synchronization.
427     *
428     * @param action a <a href="package-summary.html#NonInterference">
429     *               non-interfering</a> action to perform on the elements
430     */
431    void forEach(DoubleConsumer action);
432
433    /**
434     * Performs an action for each element of this stream, guaranteeing that
435     * each element is processed in encounter order for streams that have a
436     * defined encounter order.
437     *
438     * <p>This is a <a href="package-summary.html#StreamOps">terminal
439     * operation</a>.
440     *
441     * @param action a <a href="package-summary.html#NonInterference">
442     *               non-interfering</a> action to perform on the elements
443     * @see #forEach(DoubleConsumer)
444     */
445    void forEachOrdered(DoubleConsumer action);
446
447    /**
448     * Returns an array containing the elements of this stream.
449     *
450     * <p>This is a <a href="package-summary.html#StreamOps">terminal
451     * operation</a>.
452     *
453     * @return an array containing the elements of this stream
454     */
455    double[] toArray();
456
457    /**
458     * Performs a <a href="package-summary.html#Reduction">reduction</a> on the
459     * elements of this stream, using the provided identity value and an
460     * <a href="package-summary.html#Associativity">associative</a>
461     * accumulation function, and returns the reduced value.  This is equivalent
462     * to:
463     * <pre>{@code
464     *     double result = identity;
465     *     for (double element : this stream)
466     *         result = accumulator.applyAsDouble(result, element)
467     *     return result;
468     * }</pre>
469     *
470     * but is not constrained to execute sequentially.
471     *
472     * <p>The {@code identity} value must be an identity for the accumulator
473     * function. This means that for all {@code x},
474     * {@code accumulator.apply(identity, x)} is equal to {@code x}.
475     * The {@code accumulator} function must be an
476     * <a href="package-summary.html#Associativity">associative</a> function.
477     *
478     * <p>This is a <a href="package-summary.html#StreamOps">terminal
479     * operation</a>.
480     *
481     * @apiNote Sum, min, max, and average are all special cases of reduction.
482     * Summing a stream of numbers can be expressed as:
483
484     * <pre>{@code
485     *     double sum = numbers.reduce(0, (a, b) -> a+b);
486     * }</pre>
487     *
488     * or more compactly:
489     *
490     * <pre>{@code
491     *     double sum = numbers.reduce(0, Double::sum);
492     * }</pre>
493     *
494     * <p>While this may seem a more roundabout way to perform an aggregation
495     * compared to simply mutating a running total in a loop, reduction
496     * operations parallelize more gracefully, without needing additional
497     * synchronization and with greatly reduced risk of data races.
498     *
499     * @param identity the identity value for the accumulating function
500     * @param op an <a href="package-summary.html#Associativity">associative</a>,
501     *           <a href="package-summary.html#NonInterference">non-interfering</a>,
502     *           <a href="package-summary.html#Statelessness">stateless</a>
503     *           function for combining two values
504     * @return the result of the reduction
505     * @see #sum()
506     * @see #min()
507     * @see #max()
508     * @see #average()
509     */
510    double reduce(double identity, DoubleBinaryOperator op);
511
512    /**
513     * Performs a <a href="package-summary.html#Reduction">reduction</a> on the
514     * elements of this stream, using an
515     * <a href="package-summary.html#Associativity">associative</a> accumulation
516     * function, and returns an {@code OptionalDouble} describing the reduced
517     * value, if any. This is equivalent to:
518     * <pre>{@code
519     *     boolean foundAny = false;
520     *     double result = null;
521     *     for (double element : this stream) {
522     *         if (!foundAny) {
523     *             foundAny = true;
524     *             result = element;
525     *         }
526     *         else
527     *             result = accumulator.applyAsDouble(result, element);
528     *     }
529     *     return foundAny ? OptionalDouble.of(result) : OptionalDouble.empty();
530     * }</pre>
531     *
532     * but is not constrained to execute sequentially.
533     *
534     * <p>The {@code accumulator} function must be an
535     * <a href="package-summary.html#Associativity">associative</a> function.
536     *
537     * <p>This is a <a href="package-summary.html#StreamOps">terminal
538     * operation</a>.
539     *
540     * @param op an <a href="package-summary.html#Associativity">associative</a>,
541     *           <a href="package-summary.html#NonInterference">non-interfering</a>,
542     *           <a href="package-summary.html#Statelessness">stateless</a>
543     *           function for combining two values
544     * @return the result of the reduction
545     * @see #reduce(double, DoubleBinaryOperator)
546     */
547    OptionalDouble reduce(DoubleBinaryOperator op);
548
549    /**
550     * Performs a <a href="package-summary.html#MutableReduction">mutable
551     * reduction</a> operation on the elements of this stream.  A mutable
552     * reduction is one in which the reduced value is a mutable result container,
553     * such as an {@code ArrayList}, and elements are incorporated by updating
554     * the state of the result rather than by replacing the result.  This
555     * produces a result equivalent to:
556     * <pre>{@code
557     *     R result = supplier.get();
558     *     for (double element : this stream)
559     *         accumulator.accept(result, element);
560     *     return result;
561     * }</pre>
562     *
563     * <p>Like {@link #reduce(double, DoubleBinaryOperator)}, {@code collect}
564     * operations can be parallelized without requiring additional
565     * synchronization.
566     *
567     * <p>This is a <a href="package-summary.html#StreamOps">terminal
568     * operation</a>.
569     *
570     * @param <R> the type of the mutable result container
571     * @param supplier a function that creates a new mutable result container.
572     *                 For a parallel execution, this function may be called
573     *                 multiple times and must return a fresh value each time.
574     * @param accumulator an <a href="package-summary.html#Associativity">associative</a>,
575     *                    <a href="package-summary.html#NonInterference">non-interfering</a>,
576     *                    <a href="package-summary.html#Statelessness">stateless</a>
577     *                    function that must fold an element into a result
578     *                    container.
579     * @param combiner an <a href="package-summary.html#Associativity">associative</a>,
580     *                    <a href="package-summary.html#NonInterference">non-interfering</a>,
581     *                    <a href="package-summary.html#Statelessness">stateless</a>
582     *                    function that accepts two partial result containers
583     *                    and merges them, which must be compatible with the
584     *                    accumulator function.  The combiner function must fold
585     *                    the elements from the second result container into the
586     *                    first result container.
587     * @return the result of the reduction
588     * @see Stream#collect(Supplier, BiConsumer, BiConsumer)
589     */
590    <R> R collect(Supplier<R> supplier,
591                  ObjDoubleConsumer<R> accumulator,
592                  BiConsumer<R, R> combiner);
593
594    /**
595     * Returns the sum of elements in this stream.
596     *
597     * Summation is a special case of a <a
598     * href="package-summary.html#Reduction">reduction</a>. If
599     * floating-point summation were exact, this method would be
600     * equivalent to:
601     *
602     * <pre>{@code
603     *     return reduce(0, Double::sum);
604     * }</pre>
605     *
606     * However, since floating-point summation is not exact, the above
607     * code is not necessarily equivalent to the summation computation
608     * done by this method.
609     *
610     * <p>The value of a floating-point sum is a function both
611     * of the input values as well as the order of addition
612     * operations. The order of addition operations of this method is
613     * intentionally not defined to allow for implementation
614     * flexibility to improve the speed and accuracy of the computed
615     * result.
616     *
617     * In particular, this method may be implemented using compensated
618     * summation or other technique to reduce the error bound in the
619     * numerical sum compared to a simple summation of {@code double}
620     * values.
621     *
622     * Because of the unspecified order of operations and the
623     * possibility of using differing summation schemes, the output of
624     * this method may vary on the same input elements.
625     *
626     * <p>Various conditions can result in a non-finite sum being
627     * computed. This can occur even if the all the elements
628     * being summed are finite. If any element is non-finite,
629     * the sum will be non-finite:
630     *
631     * <ul>
632     *
633     * <li>If any element is a NaN, then the final sum will be
634     * NaN.
635     *
636     * <li>If the elements contain one or more infinities, the
637     * sum will be infinite or NaN.
638     *
639     * <ul>
640     *
641     * <li>If the elements contain infinities of opposite sign,
642     * the sum will be NaN.
643     *
644     * <li>If the elements contain infinities of one sign and
645     * an intermediate sum overflows to an infinity of the opposite
646     * sign, the sum may be NaN.
647     *
648     * </ul>
649     *
650     * </ul>
651     *
652     * It is possible for intermediate sums of finite values to
653     * overflow into opposite-signed infinities; if that occurs, the
654     * final sum will be NaN even if the elements are all
655     * finite.
656     *
657     * If all the elements are zero, the sign of zero is
658     * <em>not</em> guaranteed to be preserved in the final sum.
659     *
660     * <p>This is a <a href="package-summary.html#StreamOps">terminal
661     * operation</a>.
662     *
663     * @apiNote Elements sorted by increasing absolute magnitude tend
664     * to yield more accurate results.
665     *
666     * @return the sum of elements in this stream
667     */
668    double sum();
669
670    /**
671     * Returns an {@code OptionalDouble} describing the minimum element of this
672     * stream, or an empty OptionalDouble if this stream is empty.  The minimum
673     * element will be {@code Double.NaN} if any stream element was NaN. Unlike
674     * the numerical comparison operators, this method considers negative zero
675     * to be strictly smaller than positive zero. This is a special case of a
676     * <a href="package-summary.html#Reduction">reduction</a> and is
677     * equivalent to:
678     * <pre>{@code
679     *     return reduce(Double::min);
680     * }</pre>
681     *
682     * <p>This is a <a href="package-summary.html#StreamOps">terminal
683     * operation</a>.
684     *
685     * @return an {@code OptionalDouble} containing the minimum element of this
686     * stream, or an empty optional if the stream is empty
687     */
688    OptionalDouble min();
689
690    /**
691     * Returns an {@code OptionalDouble} describing the maximum element of this
692     * stream, or an empty OptionalDouble if this stream is empty.  The maximum
693     * element will be {@code Double.NaN} if any stream element was NaN. Unlike
694     * the numerical comparison operators, this method considers negative zero
695     * to be strictly smaller than positive zero. This is a
696     * special case of a
697     * <a href="package-summary.html#Reduction">reduction</a> and is
698     * equivalent to:
699     * <pre>{@code
700     *     return reduce(Double::max);
701     * }</pre>
702     *
703     * <p>This is a <a href="package-summary.html#StreamOps">terminal
704     * operation</a>.
705     *
706     * @return an {@code OptionalDouble} containing the maximum element of this
707     * stream, or an empty optional if the stream is empty
708     */
709    OptionalDouble max();
710
711    /**
712     * Returns the count of elements in this stream.  This is a special case of
713     * a <a href="package-summary.html#Reduction">reduction</a> and is
714     * equivalent to:
715     * <pre>{@code
716     *     return mapToLong(e -> 1L).sum();
717     * }</pre>
718     *
719     * <p>This is a <a href="package-summary.html#StreamOps">terminal operation</a>.
720     *
721     * @apiNote
722     * An implementation may choose to not execute the stream pipeline (either
723     * sequentially or in parallel) if it is capable of computing the count
724     * directly from the stream source.  In such cases no source elements will
725     * be traversed and no intermediate operations will be evaluated.
726     * Behavioral parameters with side-effects, which are strongly discouraged
727     * except for harmless cases such as debugging, may be affected.  For
728     * example, consider the following stream:
729     * <pre>{@code
730     *     DoubleStream s = DoubleStream.of(1, 2, 3, 4);
731     *     long count = s.peek(System.out::println).count();
732     * }</pre>
733     * The number of elements covered by the stream source is known and the
734     * intermediate operation, {@code peek}, does not inject into or remove
735     * elements from the stream (as may be the case for {@code flatMap} or
736     * {@code filter} operations).  Thus the count is 4 and there is no need to
737     * execute the pipeline and, as a side-effect, print out the elements.
738     *
739     * @return the count of elements in this stream
740     */
741    long count();
742
743    /**
744     * Returns an {@code OptionalDouble} describing the arithmetic
745     * mean of elements of this stream, or an empty optional if this
746     * stream is empty.
747     *
748     * <p>The computed average can vary numerically and have the
749     * special case behavior as computing the sum; see {@link #sum}
750     * for details.
751     *
752     *  <p>The average is a special case of a <a
753     *  href="package-summary.html#Reduction">reduction</a>.
754     *
755     * <p>This is a <a href="package-summary.html#StreamOps">terminal
756     * operation</a>.
757     *
758     * @apiNote Elements sorted by increasing absolute magnitude tend
759     * to yield more accurate results.
760     *
761     * @return an {@code OptionalDouble} containing the average element of this
762     * stream, or an empty optional if the stream is empty
763     */
764    OptionalDouble average();
765
766    /**
767     * Returns a {@code DoubleSummaryStatistics} describing various summary data
768     * about the elements of this stream.  This is a special
769     * case of a <a href="package-summary.html#Reduction">reduction</a>.
770     *
771     * <p>This is a <a href="package-summary.html#StreamOps">terminal
772     * operation</a>.
773     *
774     * @return a {@code DoubleSummaryStatistics} describing various summary data
775     * about the elements of this stream
776     */
777    DoubleSummaryStatistics summaryStatistics();
778
779    /**
780     * Returns whether any elements of this stream match the provided
781     * predicate.  May not evaluate the predicate on all elements if not
782     * necessary for determining the result.  If the stream is empty then
783     * {@code false} is returned and the predicate is not evaluated.
784     *
785     * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting
786     * terminal operation</a>.
787     *
788     * @apiNote
789     * This method evaluates the <em>existential quantification</em> of the
790     * predicate over the elements of the stream (for some x P(x)).
791     *
792     * @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>,
793     *                  <a href="package-summary.html#Statelessness">stateless</a>
794     *                  predicate to apply to elements of this stream
795     * @return {@code true} if any elements of the stream match the provided
796     * predicate, otherwise {@code false}
797     */
798    boolean anyMatch(DoublePredicate predicate);
799
800    /**
801     * Returns whether all elements of this stream match the provided predicate.
802     * May not evaluate the predicate on all elements if not necessary for
803     * determining the result.  If the stream is empty then {@code true} is
804     * returned and the predicate is not evaluated.
805     *
806     * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting
807     * terminal operation</a>.
808     *
809     * @apiNote
810     * This method evaluates the <em>universal quantification</em> of the
811     * predicate over the elements of the stream (for all x P(x)).  If the
812     * stream is empty, the quantification is said to be <em>vacuously
813     * satisfied</em> and is always {@code true} (regardless of P(x)).
814     *
815     * @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>,
816     *                  <a href="package-summary.html#Statelessness">stateless</a>
817     *                  predicate to apply to elements of this stream
818     * @return {@code true} if either all elements of the stream match the
819     * provided predicate or the stream is empty, otherwise {@code false}
820     */
821    boolean allMatch(DoublePredicate predicate);
822
823    /**
824     * Returns whether no elements of this stream match the provided predicate.
825     * May not evaluate the predicate on all elements if not necessary for
826     * determining the result.  If the stream is empty then {@code true} is
827     * returned and the predicate is not evaluated.
828     *
829     * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting
830     * terminal operation</a>.
831     *
832     * @apiNote
833     * This method evaluates the <em>universal quantification</em> of the
834     * negated predicate over the elements of the stream (for all x ~P(x)).  If
835     * the stream is empty, the quantification is said to be vacuously satisfied
836     * and is always {@code true}, regardless of P(x).
837     *
838     * @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>,
839     *                  <a href="package-summary.html#Statelessness">stateless</a>
840     *                  predicate to apply to elements of this stream
841     * @return {@code true} if either no elements of the stream match the
842     * provided predicate or the stream is empty, otherwise {@code false}
843     */
844    boolean noneMatch(DoublePredicate predicate);
845
846    /**
847     * Returns an {@link OptionalDouble} describing the first element of this
848     * stream, or an empty {@code OptionalDouble} if the stream is empty.  If
849     * the stream has no encounter order, then any element may be returned.
850     *
851     * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting
852     * terminal operation</a>.
853     *
854     * @return an {@code OptionalDouble} describing the first element of this
855     * stream, or an empty {@code OptionalDouble} if the stream is empty
856     */
857    OptionalDouble findFirst();
858
859    /**
860     * Returns an {@link OptionalDouble} describing some element of the stream,
861     * or an empty {@code OptionalDouble} if the stream is empty.
862     *
863     * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting
864     * terminal operation</a>.
865     *
866     * <p>The behavior of this operation is explicitly nondeterministic; it is
867     * free to select any element in the stream.  This is to allow for maximal
868     * performance in parallel operations; the cost is that multiple invocations
869     * on the same source may not return the same result.  (If a stable result
870     * is desired, use {@link #findFirst()} instead.)
871     *
872     * @return an {@code OptionalDouble} describing some element of this stream,
873     * or an empty {@code OptionalDouble} if the stream is empty
874     * @see #findFirst()
875     */
876    OptionalDouble findAny();
877
878    /**
879     * Returns a {@code Stream} consisting of the elements of this stream,
880     * boxed to {@code Double}.
881     *
882     * <p>This is an <a href="package-summary.html#StreamOps">intermediate
883     * operation</a>.
884     *
885     * @return a {@code Stream} consistent of the elements of this stream,
886     * each boxed to a {@code Double}
887     */
888    Stream<Double> boxed();
889
890    @Override
891    DoubleStream sequential();
892
893    @Override
894    DoubleStream parallel();
895
896    @Override
897    PrimitiveIterator.OfDouble iterator();
898
899    @Override
900    Spliterator.OfDouble spliterator();
901
902
903    // Static factories
904
905    /**
906     * Returns a builder for a {@code DoubleStream}.
907     *
908     * @return a stream builder
909     */
910    public static Builder builder() {
911        return new Streams.DoubleStreamBuilderImpl();
912    }
913
914    /**
915     * Returns an empty sequential {@code DoubleStream}.
916     *
917     * @return an empty sequential stream
918     */
919    public static DoubleStream empty() {
920        return StreamSupport.doubleStream(Spliterators.emptyDoubleSpliterator(), false);
921    }
922
923    /**
924     * Returns a sequential {@code DoubleStream} containing a single element.
925     *
926     * @param t the single element
927     * @return a singleton sequential stream
928     */
929    public static DoubleStream of(double t) {
930        return StreamSupport.doubleStream(new Streams.DoubleStreamBuilderImpl(t), false);
931    }
932
933    /**
934     * Returns a sequential ordered stream whose elements are the specified values.
935     *
936     * @param values the elements of the new stream
937     * @return the new stream
938     */
939    public static DoubleStream of(double... values) {
940        return Arrays.stream(values);
941    }
942
943    /**
944     * Returns an infinite sequential ordered {@code DoubleStream} produced by iterative
945     * application of a function {@code f} to an initial element {@code seed},
946     * producing a {@code Stream} consisting of {@code seed}, {@code f(seed)},
947     * {@code f(f(seed))}, etc.
948     *
949     * <p>The first element (position {@code 0}) in the {@code DoubleStream}
950     * will be the provided {@code seed}.  For {@code n > 0}, the element at
951     * position {@code n}, will be the result of applying the function {@code f}
952     *  to the element at position {@code n - 1}.
953     *
954     * <p>The action of applying {@code f} for one element
955     * <a href="../concurrent/package-summary.html#MemoryVisibility"><i>happens-before</i></a>
956     * the action of applying {@code f} for subsequent elements.  For any given
957     * element the action may be performed in whatever thread the library
958     * chooses.
959     *
960     * @param seed the initial element
961     * @param f a function to be applied to the previous element to produce
962     *          a new element
963     * @return a new sequential {@code DoubleStream}
964     */
965    public static DoubleStream iterate(final double seed, final DoubleUnaryOperator f) {
966        Objects.requireNonNull(f);
967        Spliterator.OfDouble spliterator = new Spliterators.AbstractDoubleSpliterator(Long.MAX_VALUE,
968               Spliterator.ORDERED | Spliterator.IMMUTABLE | Spliterator.NONNULL) {
969            double prev;
970            boolean started;
971
972            @Override
973            public boolean tryAdvance(DoubleConsumer action) {
974                Objects.requireNonNull(action);
975                double t;
976                if (started)
977                    t = f.applyAsDouble(prev);
978                else {
979                    t = seed;
980                    started = true;
981                }
982                action.accept(prev = t);
983                return true;
984            }
985        };
986        return StreamSupport.doubleStream(spliterator, false);
987    }
988
989    /**
990     * Returns a sequential ordered {@code DoubleStream} produced by iterative
991     * application of the given {@code next} function to an initial element,
992     * conditioned on satisfying the given {@code hasNext} predicate.  The
993     * stream terminates as soon as the {@code hasNext} predicate returns false.
994     *
995     * <p>{@code DoubleStream.iterate} should produce the same sequence of elements as
996     * produced by the corresponding for-loop:
997     * <pre>{@code
998     *     for (double index=seed; hasNext.test(index); index = next.applyAsDouble(index)) {
999     *         ...
1000     *     }
1001     * }</pre>
1002     *
1003     * <p>The resulting sequence may be empty if the {@code hasNext} predicate
1004     * does not hold on the seed value.  Otherwise the first element will be the
1005     * supplied {@code seed} value, the next element (if present) will be the
1006     * result of applying the {@code next} function to the {@code seed} value,
1007     * and so on iteratively until the {@code hasNext} predicate indicates that
1008     * the stream should terminate.
1009     *
1010     * <p>The action of applying the {@code hasNext} predicate to an element
1011     * <a href="../concurrent/package-summary.html#MemoryVisibility"><i>happens-before</i></a>
1012     * the action of applying the {@code next} function to that element.  The
1013     * action of applying the {@code next} function for one element
1014     * <i>happens-before</i> the action of applying the {@code hasNext}
1015     * predicate for subsequent elements.  For any given element an action may
1016     * be performed in whatever thread the library chooses.
1017     *
1018     * @param seed the initial element
1019     * @param hasNext a predicate to apply to elements to determine when the
1020     *                stream must terminate.
1021     * @param next a function to be applied to the previous element to produce
1022     *             a new element
1023     * @return a new sequential {@code DoubleStream}
1024     * @since 9
1025     */
1026    public static DoubleStream iterate(double seed, DoublePredicate hasNext, DoubleUnaryOperator next) {
1027        Objects.requireNonNull(next);
1028        Objects.requireNonNull(hasNext);
1029        Spliterator.OfDouble spliterator = new Spliterators.AbstractDoubleSpliterator(Long.MAX_VALUE,
1030               Spliterator.ORDERED | Spliterator.IMMUTABLE | Spliterator.NONNULL) {
1031            double prev;
1032            boolean started, finished;
1033
1034            @Override
1035            public boolean tryAdvance(DoubleConsumer action) {
1036                Objects.requireNonNull(action);
1037                if (finished)
1038                    return false;
1039                double t;
1040                if (started)
1041                    t = next.applyAsDouble(prev);
1042                else {
1043                    t = seed;
1044                    started = true;
1045                }
1046                if (!hasNext.test(t)) {
1047                    finished = true;
1048                    return false;
1049                }
1050                action.accept(prev = t);
1051                return true;
1052            }
1053
1054            @Override
1055            public void forEachRemaining(DoubleConsumer action) {
1056                Objects.requireNonNull(action);
1057                if (finished)
1058                    return;
1059                finished = true;
1060                double t = started ? next.applyAsDouble(prev) : seed;
1061                while (hasNext.test(t)) {
1062                    action.accept(t);
1063                    t = next.applyAsDouble(t);
1064                }
1065            }
1066        };
1067        return StreamSupport.doubleStream(spliterator, false);
1068    }
1069
1070    /**
1071     * Returns an infinite sequential unordered stream where each element is
1072     * generated by the provided {@code DoubleSupplier}.  This is suitable for
1073     * generating constant streams, streams of random elements, etc.
1074     *
1075     * @param s the {@code DoubleSupplier} for generated elements
1076     * @return a new infinite sequential unordered {@code DoubleStream}
1077     */
1078    public static DoubleStream generate(DoubleSupplier s) {
1079        Objects.requireNonNull(s);
1080        return StreamSupport.doubleStream(
1081                new StreamSpliterators.InfiniteSupplyingSpliterator.OfDouble(Long.MAX_VALUE, s), false);
1082    }
1083
1084    /**
1085     * Creates a lazily concatenated stream whose elements are all the
1086     * elements of the first stream followed by all the elements of the
1087     * second stream.  The resulting stream is ordered if both
1088     * of the input streams are ordered, and parallel if either of the input
1089     * streams is parallel.  When the resulting stream is closed, the close
1090     * handlers for both input streams are invoked.
1091     *
1092     * @implNote
1093     * Use caution when constructing streams from repeated concatenation.
1094     * Accessing an element of a deeply concatenated stream can result in deep
1095     * call chains, or even {@code StackOverflowError}.
1096     *
1097     * @param a the first stream
1098     * @param b the second stream
1099     * @return the concatenation of the two input streams
1100     */
1101    public static DoubleStream concat(DoubleStream a, DoubleStream b) {
1102        Objects.requireNonNull(a);
1103        Objects.requireNonNull(b);
1104
1105        Spliterator.OfDouble split = new Streams.ConcatSpliterator.OfDouble(
1106                a.spliterator(), b.spliterator());
1107        DoubleStream stream = StreamSupport.doubleStream(split, a.isParallel() || b.isParallel());
1108        return stream.onClose(Streams.composedClose(a, b));
1109    }
1110
1111    /**
1112     * A mutable builder for a {@code DoubleStream}.
1113     *
1114     * <p>A stream builder has a lifecycle, which starts in a building
1115     * phase, during which elements can be added, and then transitions to a built
1116     * phase, after which elements may not be added.  The built phase
1117     * begins when the {@link #build()} method is called, which creates an
1118     * ordered stream whose elements are the elements that were added to the
1119     * stream builder, in the order they were added.
1120     *
1121     * @see DoubleStream#builder()
1122     * @since 1.8
1123     */
1124    public interface Builder extends DoubleConsumer {
1125
1126        /**
1127         * Adds an element to the stream being built.
1128         *
1129         * @throws IllegalStateException if the builder has already transitioned
1130         * to the built state
1131         */
1132        @Override
1133        void accept(double t);
1134
1135        /**
1136         * Adds an element to the stream being built.
1137         *
1138         * @implSpec
1139         * The default implementation behaves as if:
1140         * <pre>{@code
1141         *     accept(t)
1142         *     return this;
1143         * }</pre>
1144         *
1145         * @param t the element to add
1146         * @return {@code this} builder
1147         * @throws IllegalStateException if the builder has already transitioned
1148         * to the built state
1149         */
1150        default Builder add(double t) {
1151            accept(t);
1152            return this;
1153        }
1154
1155        /**
1156         * Builds the stream, transitioning this builder to the built state.
1157         * An {@code IllegalStateException} is thrown if there are further
1158         * attempts to operate on the builder after it has entered the built
1159         * state.
1160         *
1161         * @return the built stream
1162         * @throws IllegalStateException if the builder has already transitioned
1163         * to the built state
1164         */
1165        DoubleStream build();
1166    }
1167}
1168