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. The sum returned can vary 506 * depending upon the order in which elements are encountered. This is due 507 * to accumulated rounding error in addition of values of differing 508 * magnitudes. Elements sorted by increasing absolute magnitude tend to 509 * yield more accurate results. If any stream element is a {@code NaN} or 510 * the sum is at any point a {@code NaN} then the sum will be {@code NaN}. 511 * This is a special case of a 512 * <a href="package-summary.html#Reduction">reduction</a> and is 513 * equivalent to: 514 * <pre>{@code 515 * return reduce(0, Double::sum); 516 * }</pre> 517 * 518 * <p>This is a <a href="package-summary.html#StreamOps">terminal 519 * operation</a>. 520 * 521 * @return the sum of elements in this stream 522 */ 523 double sum(); 524 525 /** 526 * Returns an {@code OptionalDouble} describing the minimum element of this 527 * stream, or an empty OptionalDouble if this stream is empty. The minimum 528 * element will be {@code Double.NaN} if any stream element was NaN. Unlike 529 * the numerical comparison operators, this method considers negative zero 530 * to be strictly smaller than positive zero. This is a special case of a 531 * <a href="package-summary.html#Reduction">reduction</a> and is 532 * equivalent to: 533 * <pre>{@code 534 * return reduce(Double::min); 535 * }</pre> 536 * 537 * <p>This is a <a href="package-summary.html#StreamOps">terminal 538 * operation</a>. 539 * 540 * @return an {@code OptionalDouble} containing the minimum element of this 541 * stream, or an empty optional if the stream is empty 542 */ 543 OptionalDouble min(); 544 545 /** 546 * Returns an {@code OptionalDouble} describing the maximum element of this 547 * stream, or an empty OptionalDouble if this stream is empty. The maximum 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 551 * special case of a 552 * <a href="package-summary.html#Reduction">reduction</a> and is 553 * equivalent to: 554 * <pre>{@code 555 * return reduce(Double::max); 556 * }</pre> 557 * 558 * <p>This is a <a href="package-summary.html#StreamOps">terminal 559 * operation</a>. 560 * 561 * @return an {@code OptionalDouble} containing the maximum element of this 562 * stream, or an empty optional if the stream is empty 563 */ 564 OptionalDouble max(); 565 566 /** 567 * Returns the count of elements in this stream. This is a special case of 568 * a <a href="package-summary.html#Reduction">reduction</a> and is 569 * equivalent to: 570 * <pre>{@code 571 * return mapToLong(e -> 1L).sum(); 572 * }</pre> 573 * 574 * <p>This is a <a href="package-summary.html#StreamOps">terminal operation</a>. 575 * 576 * @return the count of elements in this stream 577 */ 578 long count(); 579 580 /** 581 * Returns an {@code OptionalDouble} describing the arithmetic mean of elements of 582 * this stream, or an empty optional if this stream is empty. The average 583 * returned can vary depending upon the order in which elements are 584 * encountered. This is due to accumulated rounding error in addition of 585 * elements of differing magnitudes. Elements sorted by increasing absolute 586 * magnitude tend to yield more accurate results. If any recorded value is 587 * a {@code NaN} or the sum is at any point a {@code NaN} then the average 588 * will be {@code NaN}. This is a special case of a 589 * <a href="package-summary.html#Reduction">reduction</a>. 590 * 591 * <p>This is a <a href="package-summary.html#StreamOps">terminal 592 * operation</a>. 593 * 594 * @return an {@code OptionalDouble} containing the average element of this 595 * stream, or an empty optional if the stream is empty 596 */ 597 OptionalDouble average(); 598 599 /** 600 * Returns a {@code DoubleSummaryStatistics} describing various summary data 601 * about the elements of this stream. This is a special 602 * case of a <a href="package-summary.html#Reduction">reduction</a>. 603 * 604 * <p>This is a <a href="package-summary.html#StreamOps">terminal 605 * operation</a>. 606 * 607 * @return a {@code DoubleSummaryStatistics} describing various summary data 608 * about the elements of this stream 609 */ 610 DoubleSummaryStatistics summaryStatistics(); 611 612 /** 613 * Returns whether any elements of this stream match the provided 614 * predicate. May not evaluate the predicate on all elements if not 615 * necessary for determining the result. 616 * 617 * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting 618 * terminal operation</a>. 619 * 620 * @param predicate a <a href="package-summary.html#NonInterference">non-interfering, 621 * stateless</a> predicate to apply to elements of this 622 * stream 623 * @return {@code true} if any elements of the stream match the provided 624 * predicate otherwise {@code false} 625 */ 626 boolean anyMatch(DoublePredicate predicate); 627 628 /** 629 * Returns whether all elements of this stream match the provided predicate. 630 * May not evaluate the predicate on all elements if not necessary for 631 * determining the result. 632 * 633 * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting 634 * terminal operation</a>. 635 * 636 * @param predicate a <a href="package-summary.html#NonInterference">non-interfering, 637 * stateless</a> predicate to apply to elements of this 638 * stream 639 * @return {@code true} if all elements of the stream match the provided 640 * predicate otherwise {@code false} 641 */ 642 boolean allMatch(DoublePredicate predicate); 643 644 /** 645 * Returns whether no elements of this stream match the provided predicate. 646 * May not evaluate the predicate on all elements if not necessary for 647 * determining the result. 648 * 649 * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting 650 * terminal operation</a>. 651 * 652 * @param predicate a <a href="package-summary.html#NonInterference">non-interfering, 653 * stateless</a> predicate to apply to elements of this 654 * stream 655 * @return {@code true} if no elements of the stream match the provided 656 * predicate 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 a sequential stream where each element is generated by 797 * the provided {@code DoubleSupplier}. This is suitable for generating 798 * constant streams, streams of random elements, etc. 799 * 800 * @param s the {@code DoubleSupplier} for generated elements 801 * @return a new sequential {@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 * @param a the first stream 818 * @param b the second stream 819 * @return the concatenation of the two input streams 820 */ 821 public static DoubleStream concat(DoubleStream a, DoubleStream b) { 822 Objects.requireNonNull(a); 823 Objects.requireNonNull(b); 824 825 Spliterator.OfDouble split = new Streams.ConcatSpliterator.OfDouble( 826 a.spliterator(), b.spliterator()); 827 DoubleStream stream = StreamSupport.doubleStream(split, a.isParallel() || b.isParallel()); 828 return stream.onClose(Streams.composedClose(a, b)); 829 } 830 831 /** 832 * A mutable builder for a {@code DoubleStream}. 833 * 834 * <p>A stream builder has a lifecycle, which starts in a building 835 * phase, during which elements can be added, and then transitions to a built 836 * phase, after which elements may not be added. The built phase 837 * begins when the {@link #build()} method is called, which creates an 838 * ordered stream whose elements are the elements that were added to the 839 * stream builder, in the order they were added. 840 * 841 * @see DoubleStream#builder() 842 * @since 1.8 843 */ 844 public interface Builder extends DoubleConsumer { 845 846 /** 847 * Adds an element to the stream being built. 848 * 849 * @throws IllegalStateException if the builder has already transitioned 850 * to the built state 851 */ 852 @Override 853 void accept(double t); 854 855 /** 856 * Adds an element to the stream being built. 857 * 858 * @implSpec 859 * The default implementation behaves as if: 860 * <pre>{@code 861 * accept(t) 862 * return this; 863 * }</pre> 864 * 865 * @param t the element to add 866 * @return {@code this} builder 867 * @throws IllegalStateException if the builder has already transitioned 868 * to the built state 869 */ 870 default Builder add(double t) { 871 accept(t); 872 return this; 873 } 874 875 /** 876 * Builds the stream, transitioning this builder to the built state. 877 * An {@code IllegalStateException} is thrown if there are further 878 * attempts to operate on the builder after it has entered the built 879 * state. 880 * 881 * @return the built stream 882 * @throws IllegalStateException if the builder has already transitioned 883 * to the built state 884 */ 885 DoubleStream build(); 886 } 887 }