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