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