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