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