1 /* 2 * Copyright (c) 2012, 2020, 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 */ filter(IntPredicate predicate)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 */ map(IntUnaryOperator mapper)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 */ mapToObj(IntFunction<? extends U> mapper)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 */ mapToLong(IntToLongFunction mapper)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 */ mapToDouble(IntToDoubleFunction mapper)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 */ flatMap(IntFunction<? extends IntStream> mapper)165 IntStream flatMap(IntFunction<? extends IntStream> mapper); 166 167 /** 168 * Returns a stream consisting of the results of replacing each element of 169 * this stream with multiple elements, specifically zero or more elements. 170 * Replacement is performed by applying the provided mapping function to each 171 * element in conjunction with a {@linkplain IntConsumer consumer} argument 172 * that accepts replacement elements. The mapping function calls the consumer 173 * zero or more times to provide the replacement elements. 174 * 175 * <p>This is an <a href="package-summary.html#StreamOps">intermediate 176 * operation</a>. 177 * 178 * <p>If the {@linkplain IntConsumer consumer} argument is used outside the scope of 179 * its application to the mapping function, the results are undefined. 180 * 181 * @implSpec 182 * The default implementation invokes {@link #flatMap flatMap} on this stream, 183 * passing a function that behaves as follows. First, it calls the mapper function 184 * with an {@code IntConsumer} that accumulates replacement elements into a newly created 185 * internal buffer. When the mapper function returns, it creates an {@code IntStream} from the 186 * internal buffer. Finally, it returns this stream to {@code flatMap}. 187 * 188 * @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>, 189 * <a href="package-summary.html#Statelessness">stateless</a> 190 * function that generates replacement elements 191 * @return the new stream 192 * @see Stream#mapMulti Stream.mapMulti 193 * @since 16 194 */ mapMulti(IntMapMultiConsumer mapper)195 default IntStream mapMulti(IntMapMultiConsumer mapper) { 196 Objects.requireNonNull(mapper); 197 return flatMap(e -> { 198 SpinedBuffer.OfInt buffer = new SpinedBuffer.OfInt(); 199 mapper.accept(e, buffer); 200 return StreamSupport.intStream(buffer.spliterator(), false); 201 }); 202 } 203 204 /** 205 * Returns a stream consisting of the distinct elements of this stream. 206 * 207 * <p>This is a <a href="package-summary.html#StreamOps">stateful 208 * intermediate operation</a>. 209 * 210 * @return the new stream 211 */ distinct()212 IntStream distinct(); 213 214 /** 215 * Returns a stream consisting of the elements of this stream in sorted 216 * order. 217 * 218 * <p>This is a <a href="package-summary.html#StreamOps">stateful 219 * intermediate operation</a>. 220 * 221 * @return the new stream 222 */ sorted()223 IntStream sorted(); 224 225 /** 226 * Returns a stream consisting of the elements of this stream, additionally 227 * performing the provided action on each element as elements are consumed 228 * from the resulting stream. 229 * 230 * <p>This is an <a href="package-summary.html#StreamOps">intermediate 231 * operation</a>. 232 * 233 * <p>For parallel stream pipelines, the action may be called at 234 * whatever time and in whatever thread the element is made available by the 235 * upstream operation. If the action modifies shared state, 236 * it is responsible for providing the required synchronization. 237 * 238 * @apiNote This method exists mainly to support debugging, where you want 239 * to see the elements as they flow past a certain point in a pipeline: 240 * <pre>{@code 241 * IntStream.of(1, 2, 3, 4) 242 * .filter(e -> e > 2) 243 * .peek(e -> System.out.println("Filtered value: " + e)) 244 * .map(e -> e * e) 245 * .peek(e -> System.out.println("Mapped value: " + e)) 246 * .sum(); 247 * }</pre> 248 * 249 * <p>In cases where the stream implementation is able to optimize away the 250 * production of some or all the elements (such as with short-circuiting 251 * operations like {@code findFirst}, or in the example described in 252 * {@link #count}), the action will not be invoked for those elements. 253 * 254 * @param action a <a href="package-summary.html#NonInterference"> 255 * non-interfering</a> action to perform on the elements as 256 * they are consumed from the stream 257 * @return the new stream 258 */ peek(IntConsumer action)259 IntStream peek(IntConsumer action); 260 261 /** 262 * Returns a stream consisting of the elements of this stream, truncated 263 * to be no longer than {@code maxSize} in length. 264 * 265 * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting 266 * stateful intermediate operation</a>. 267 * 268 * @apiNote 269 * While {@code limit()} is generally a cheap operation on sequential 270 * stream pipelines, it can be quite expensive on ordered parallel pipelines, 271 * especially for large values of {@code maxSize}, since {@code limit(n)} 272 * is constrained to return not just any <em>n</em> elements, but the 273 * <em>first n</em> elements in the encounter order. Using an unordered 274 * stream source (such as {@link #generate(IntSupplier)}) or removing the 275 * ordering constraint with {@link #unordered()} may result in significant 276 * speedups of {@code limit()} in parallel pipelines, if the semantics of 277 * your situation permit. If consistency with encounter order is required, 278 * and you are experiencing poor performance or memory utilization with 279 * {@code limit()} in parallel pipelines, switching to sequential execution 280 * with {@link #sequential()} may improve performance. 281 * 282 * @param maxSize the number of elements the stream should be limited to 283 * @return the new stream 284 * @throws IllegalArgumentException if {@code maxSize} is negative 285 */ limit(long maxSize)286 IntStream limit(long maxSize); 287 288 /** 289 * Returns a stream consisting of the remaining elements of this stream 290 * after discarding the first {@code n} elements of the stream. 291 * If this stream contains fewer than {@code n} elements then an 292 * empty stream will be returned. 293 * 294 * <p>This is a <a href="package-summary.html#StreamOps">stateful 295 * intermediate operation</a>. 296 * 297 * @apiNote 298 * While {@code skip()} is generally a cheap operation on sequential 299 * stream pipelines, it can be quite expensive on ordered parallel pipelines, 300 * especially for large values of {@code n}, since {@code skip(n)} 301 * is constrained to skip not just any <em>n</em> elements, but the 302 * <em>first n</em> elements in the encounter order. Using an unordered 303 * stream source (such as {@link #generate(IntSupplier)}) or removing the 304 * ordering constraint with {@link #unordered()} may result in significant 305 * speedups of {@code skip()} in parallel pipelines, if the semantics of 306 * your situation permit. If consistency with encounter order is required, 307 * and you are experiencing poor performance or memory utilization with 308 * {@code skip()} in parallel pipelines, switching to sequential execution 309 * with {@link #sequential()} may improve performance. 310 * 311 * @param n the number of leading elements to skip 312 * @return the new stream 313 * @throws IllegalArgumentException if {@code n} is negative 314 */ skip(long n)315 IntStream skip(long n); 316 317 /** 318 * Returns, if this stream is ordered, a stream consisting of the longest 319 * prefix of elements taken from this stream that match the given predicate. 320 * Otherwise returns, if this stream is unordered, a stream consisting of a 321 * subset of elements taken from this stream that match the given predicate. 322 * 323 * <p>If this stream is ordered then the longest prefix is a contiguous 324 * sequence of elements of this stream that match the given predicate. The 325 * first element of the sequence is the first element of this stream, and 326 * the element immediately following the last element of the sequence does 327 * not match the given predicate. 328 * 329 * <p>If this stream is unordered, and some (but not all) elements of this 330 * stream match the given predicate, then the behavior of this operation is 331 * nondeterministic; it is free to take any subset of matching elements 332 * (which includes the empty set). 333 * 334 * <p>Independent of whether this stream is ordered or unordered if all 335 * elements of this stream match the given predicate then this operation 336 * takes all elements (the result is the same as the input), or if no 337 * elements of the stream match the given predicate then no elements are 338 * taken (the result is an empty stream). 339 * 340 * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting 341 * stateful intermediate operation</a>. 342 * 343 * @implSpec 344 * The default implementation obtains the {@link #spliterator() spliterator} 345 * of this stream, wraps that spliterator so as to support the semantics 346 * of this operation on traversal, and returns a new stream associated with 347 * the wrapped spliterator. The returned stream preserves the execution 348 * characteristics of this stream (namely parallel or sequential execution 349 * as per {@link #isParallel()}) but the wrapped spliterator may choose to 350 * not support splitting. When the returned stream is closed, the close 351 * handlers for both the returned and this stream are invoked. 352 * 353 * @apiNote 354 * While {@code takeWhile()} is generally a cheap operation on sequential 355 * stream pipelines, it can be quite expensive on ordered parallel 356 * pipelines, since the operation is constrained to return not just any 357 * valid prefix, but the longest prefix of elements in the encounter order. 358 * Using an unordered stream source (such as {@link #generate(IntSupplier)}) 359 * or removing the ordering constraint with {@link #unordered()} may result 360 * in significant speedups of {@code takeWhile()} in parallel pipelines, if 361 * the semantics of your situation permit. If consistency with encounter 362 * order is required, and you are experiencing poor performance or memory 363 * utilization with {@code takeWhile()} in parallel pipelines, switching to 364 * sequential execution with {@link #sequential()} may improve performance. 365 * 366 * @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>, 367 * <a href="package-summary.html#Statelessness">stateless</a> 368 * predicate to apply to elements to determine the longest 369 * prefix of elements. 370 * @return the new stream 371 * @since 9 372 */ takeWhile(IntPredicate predicate)373 default IntStream takeWhile(IntPredicate predicate) { 374 Objects.requireNonNull(predicate); 375 // Reuses the unordered spliterator, which, when encounter is present, 376 // is safe to use as long as it configured not to split 377 return StreamSupport.intStream( 378 new WhileOps.UnorderedWhileSpliterator.OfInt.Taking(spliterator(), true, predicate), 379 isParallel()).onClose(this::close); 380 } 381 382 /** 383 * Returns, if this stream is ordered, a stream consisting of the remaining 384 * elements of this stream after dropping the longest prefix of elements 385 * that match the given predicate. Otherwise returns, if this stream is 386 * unordered, a stream consisting of the remaining elements of this stream 387 * after dropping a subset of elements that match the given predicate. 388 * 389 * <p>If this stream is ordered then the longest prefix is a contiguous 390 * sequence of elements of this stream that match the given predicate. The 391 * first element of the sequence is the first element of this stream, and 392 * the element immediately following the last element of the sequence does 393 * not match the given predicate. 394 * 395 * <p>If this stream is unordered, and some (but not all) elements of this 396 * stream match the given predicate, then the behavior of this operation is 397 * nondeterministic; it is free to drop any subset of matching elements 398 * (which includes the empty set). 399 * 400 * <p>Independent of whether this stream is ordered or unordered if all 401 * elements of this stream match the given predicate then this operation 402 * drops all elements (the result is an empty stream), or if no elements of 403 * the stream match the given predicate then no elements are dropped (the 404 * result is the same as the input). 405 * 406 * <p>This is a <a href="package-summary.html#StreamOps">stateful 407 * intermediate operation</a>. 408 * 409 * @implSpec 410 * The default implementation obtains the {@link #spliterator() spliterator} 411 * of this stream, wraps that spliterator so as to support the semantics 412 * of this operation on traversal, and returns a new stream associated with 413 * the wrapped spliterator. The returned stream preserves the execution 414 * characteristics of this stream (namely parallel or sequential execution 415 * as per {@link #isParallel()}) but the wrapped spliterator may choose to 416 * not support splitting. When the returned stream is closed, the close 417 * handlers for both the returned and this stream are invoked. 418 * 419 * @apiNote 420 * While {@code dropWhile()} is generally a cheap operation on sequential 421 * stream pipelines, it can be quite expensive on ordered parallel 422 * pipelines, since the operation is constrained to return not just any 423 * valid prefix, but the longest prefix of elements in the encounter order. 424 * Using an unordered stream source (such as {@link #generate(IntSupplier)}) 425 * or removing the ordering constraint with {@link #unordered()} may result 426 * in significant speedups of {@code dropWhile()} in parallel pipelines, if 427 * the semantics of your situation permit. If consistency with encounter 428 * order is required, and you are experiencing poor performance or memory 429 * utilization with {@code dropWhile()} in parallel pipelines, switching to 430 * sequential execution with {@link #sequential()} may improve performance. 431 * 432 * @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>, 433 * <a href="package-summary.html#Statelessness">stateless</a> 434 * predicate to apply to elements to determine the longest 435 * prefix of elements. 436 * @return the new stream 437 * @since 9 438 */ dropWhile(IntPredicate predicate)439 default IntStream dropWhile(IntPredicate predicate) { 440 Objects.requireNonNull(predicate); 441 // Reuses the unordered spliterator, which, when encounter is present, 442 // is safe to use as long as it configured not to split 443 return StreamSupport.intStream( 444 new WhileOps.UnorderedWhileSpliterator.OfInt.Dropping(spliterator(), true, predicate), 445 isParallel()).onClose(this::close); 446 } 447 448 /** 449 * Performs an action for each element of this stream. 450 * 451 * <p>This is a <a href="package-summary.html#StreamOps">terminal 452 * operation</a>. 453 * 454 * <p>For parallel stream pipelines, this operation does <em>not</em> 455 * guarantee to respect the encounter order of the stream, as doing so 456 * would sacrifice the benefit of parallelism. For any given element, the 457 * action may be performed at whatever time and in whatever thread the 458 * library chooses. If the action accesses shared state, it is 459 * responsible for providing the required synchronization. 460 * 461 * @param action a <a href="package-summary.html#NonInterference"> 462 * non-interfering</a> action to perform on the elements 463 */ forEach(IntConsumer action)464 void forEach(IntConsumer action); 465 466 /** 467 * Performs an action for each element of this stream, guaranteeing that 468 * each element is processed in encounter order for streams that have a 469 * defined encounter order. 470 * 471 * <p>This is a <a href="package-summary.html#StreamOps">terminal 472 * operation</a>. 473 * 474 * @param action a <a href="package-summary.html#NonInterference"> 475 * non-interfering</a> action to perform on the elements 476 * @see #forEach(IntConsumer) 477 */ forEachOrdered(IntConsumer action)478 void forEachOrdered(IntConsumer action); 479 480 /** 481 * Returns an array containing the elements of this stream. 482 * 483 * <p>This is a <a href="package-summary.html#StreamOps">terminal 484 * operation</a>. 485 * 486 * @return an array containing the elements of this stream 487 */ toArray()488 int[] toArray(); 489 490 /** 491 * Performs a <a href="package-summary.html#Reduction">reduction</a> on the 492 * elements of this stream, using the provided identity value and an 493 * <a href="package-summary.html#Associativity">associative</a> 494 * accumulation function, and returns the reduced value. This is equivalent 495 * to: 496 * <pre>{@code 497 * int result = identity; 498 * for (int element : this stream) 499 * result = accumulator.applyAsInt(result, element) 500 * return result; 501 * }</pre> 502 * 503 * but is not constrained to execute sequentially. 504 * 505 * <p>The {@code identity} value must be an identity for the accumulator 506 * function. This means that for all {@code x}, 507 * {@code accumulator.apply(identity, x)} is equal to {@code x}. 508 * The {@code accumulator} function must be an 509 * <a href="package-summary.html#Associativity">associative</a> function. 510 * 511 * <p>This is a <a href="package-summary.html#StreamOps">terminal 512 * operation</a>. 513 * 514 * @apiNote Sum, min and max are all special cases of reduction that can be 515 * expressed using this method. 516 * For example, summing a stream can be expressed as: 517 * 518 * <pre>{@code 519 * int sum = integers.reduce(0, (a, b) -> a+b); 520 * }</pre> 521 * 522 * or more compactly: 523 * 524 * <pre>{@code 525 * int sum = integers.reduce(0, Integer::sum); 526 * }</pre> 527 * 528 * <p>While this may seem a more roundabout way to perform an aggregation 529 * compared to simply mutating a running total in a loop, reduction 530 * operations parallelize more gracefully, without needing additional 531 * synchronization and with greatly reduced risk of data races. 532 * 533 * @param identity the identity value for the accumulating function 534 * @param op an <a href="package-summary.html#Associativity">associative</a>, 535 * <a href="package-summary.html#NonInterference">non-interfering</a>, 536 * <a href="package-summary.html#Statelessness">stateless</a> 537 * function for combining two values 538 * @return the result of the reduction 539 * @see #sum() 540 * @see #min() 541 * @see #max() 542 * @see #average() 543 */ reduce(int identity, IntBinaryOperator op)544 int reduce(int identity, IntBinaryOperator op); 545 546 /** 547 * Performs a <a href="package-summary.html#Reduction">reduction</a> on the 548 * elements of this stream, using an 549 * <a href="package-summary.html#Associativity">associative</a> accumulation 550 * function, and returns an {@code OptionalInt} describing the reduced value, 551 * if any. This is equivalent to: 552 * <pre>{@code 553 * boolean foundAny = false; 554 * int result = null; 555 * for (int element : this stream) { 556 * if (!foundAny) { 557 * foundAny = true; 558 * result = element; 559 * } 560 * else 561 * result = accumulator.applyAsInt(result, element); 562 * } 563 * return foundAny ? OptionalInt.of(result) : OptionalInt.empty(); 564 * }</pre> 565 * 566 * but is not constrained to execute sequentially. 567 * 568 * <p>The {@code accumulator} function must be an 569 * <a href="package-summary.html#Associativity">associative</a> function. 570 * 571 * <p>This is a <a href="package-summary.html#StreamOps">terminal 572 * operation</a>. 573 * 574 * @param op an <a href="package-summary.html#Associativity">associative</a>, 575 * <a href="package-summary.html#NonInterference">non-interfering</a>, 576 * <a href="package-summary.html#Statelessness">stateless</a> 577 * function for combining two values 578 * @return the result of the reduction 579 * @see #reduce(int, IntBinaryOperator) 580 */ reduce(IntBinaryOperator op)581 OptionalInt reduce(IntBinaryOperator op); 582 583 /** 584 * Performs a <a href="package-summary.html#MutableReduction">mutable 585 * reduction</a> operation on the elements of this stream. A mutable 586 * reduction is one in which the reduced value is a mutable result container, 587 * such as an {@code ArrayList}, and elements are incorporated by updating 588 * the state of the result rather than by replacing the result. This 589 * produces a result equivalent to: 590 * <pre>{@code 591 * R result = supplier.get(); 592 * for (int element : this stream) 593 * accumulator.accept(result, element); 594 * return result; 595 * }</pre> 596 * 597 * <p>Like {@link #reduce(int, IntBinaryOperator)}, {@code collect} operations 598 * can be parallelized without requiring additional synchronization. 599 * 600 * <p>This is a <a href="package-summary.html#StreamOps">terminal 601 * operation</a>. 602 * 603 * @param <R> the type of the mutable result container 604 * @param supplier a function that creates a new mutable result container. 605 * For a parallel execution, this function may be called 606 * multiple times and must return a fresh value each time. 607 * @param accumulator an <a href="package-summary.html#Associativity">associative</a>, 608 * <a href="package-summary.html#NonInterference">non-interfering</a>, 609 * <a href="package-summary.html#Statelessness">stateless</a> 610 * function that must fold an element into a result 611 * container. 612 * @param combiner an <a href="package-summary.html#Associativity">associative</a>, 613 * <a href="package-summary.html#NonInterference">non-interfering</a>, 614 * <a href="package-summary.html#Statelessness">stateless</a> 615 * function that accepts two partial result containers 616 * and merges them, which must be compatible with the 617 * accumulator function. The combiner function must fold 618 * the elements from the second result container into the 619 * first result container. 620 * @return the result of the reduction 621 * @see Stream#collect(Supplier, BiConsumer, BiConsumer) 622 */ collect(Supplier<R> supplier, ObjIntConsumer<R> accumulator, BiConsumer<R, R> combiner)623 <R> R collect(Supplier<R> supplier, 624 ObjIntConsumer<R> accumulator, 625 BiConsumer<R, R> combiner); 626 627 /** 628 * Returns the sum of elements in this stream. This is a special case 629 * of a <a href="package-summary.html#Reduction">reduction</a> 630 * and is equivalent to: 631 * <pre>{@code 632 * return reduce(0, Integer::sum); 633 * }</pre> 634 * 635 * <p>This is a <a href="package-summary.html#StreamOps">terminal 636 * operation</a>. 637 * 638 * @return the sum of elements in this stream 639 */ sum()640 int sum(); 641 642 /** 643 * Returns an {@code OptionalInt} describing the minimum element of this 644 * stream, or an empty optional if this stream is empty. This is a special 645 * case of a <a href="package-summary.html#Reduction">reduction</a> 646 * and is equivalent to: 647 * <pre>{@code 648 * return reduce(Integer::min); 649 * }</pre> 650 * 651 * <p>This is a <a href="package-summary.html#StreamOps">terminal operation</a>. 652 * 653 * @return an {@code OptionalInt} containing the minimum element of this 654 * stream, or an empty {@code OptionalInt} if the stream is empty 655 */ min()656 OptionalInt min(); 657 658 /** 659 * Returns an {@code OptionalInt} describing the maximum element of this 660 * stream, or an empty optional if this stream is empty. This is a special 661 * case of a <a href="package-summary.html#Reduction">reduction</a> 662 * and is equivalent to: 663 * <pre>{@code 664 * return reduce(Integer::max); 665 * }</pre> 666 * 667 * <p>This is a <a href="package-summary.html#StreamOps">terminal 668 * operation</a>. 669 * 670 * @return an {@code OptionalInt} containing the maximum element of this 671 * stream, or an empty {@code OptionalInt} if the stream is empty 672 */ max()673 OptionalInt max(); 674 675 /** 676 * Returns the count of elements in this stream. This is a special case of 677 * a <a href="package-summary.html#Reduction">reduction</a> and is 678 * equivalent to: 679 * <pre>{@code 680 * return mapToLong(e -> 1L).sum(); 681 * }</pre> 682 * 683 * <p>This is a <a href="package-summary.html#StreamOps">terminal operation</a>. 684 * 685 * @apiNote 686 * An implementation may choose to not execute the stream pipeline (either 687 * sequentially or in parallel) if it is capable of computing the count 688 * directly from the stream source. In such cases no source elements will 689 * be traversed and no intermediate operations will be evaluated. 690 * Behavioral parameters with side-effects, which are strongly discouraged 691 * except for harmless cases such as debugging, may be affected. For 692 * example, consider the following stream: 693 * <pre>{@code 694 * IntStream s = IntStream.of(1, 2, 3, 4); 695 * long count = s.peek(System.out::println).count(); 696 * }</pre> 697 * The number of elements covered by the stream source is known and the 698 * intermediate operation, {@code peek}, does not inject into or remove 699 * elements from the stream (as may be the case for {@code flatMap} or 700 * {@code filter} operations). Thus the count is 4 and there is no need to 701 * execute the pipeline and, as a side-effect, print out the elements. 702 * 703 * @return the count of elements in this stream 704 */ count()705 long count(); 706 707 /** 708 * Returns an {@code OptionalDouble} describing the arithmetic mean of elements of 709 * this stream, or an empty optional if this stream is empty. This is a 710 * special case of a 711 * <a href="package-summary.html#Reduction">reduction</a>. 712 * 713 * <p>This is a <a href="package-summary.html#StreamOps">terminal 714 * operation</a>. 715 * 716 * @return an {@code OptionalDouble} containing the average element of this 717 * stream, or an empty optional if the stream is empty 718 */ average()719 OptionalDouble average(); 720 721 /** 722 * Returns an {@code IntSummaryStatistics} describing various 723 * summary data about the elements of this stream. This is a special 724 * case of a <a href="package-summary.html#Reduction">reduction</a>. 725 * 726 * <p>This is a <a href="package-summary.html#StreamOps">terminal 727 * operation</a>. 728 * 729 * @return an {@code IntSummaryStatistics} describing various summary data 730 * about the elements of this stream 731 */ summaryStatistics()732 IntSummaryStatistics summaryStatistics(); 733 734 /** 735 * Returns whether any elements of this stream match the provided 736 * predicate. May not evaluate the predicate on all elements if not 737 * necessary for determining the result. If the stream is empty then 738 * {@code false} is returned and the predicate is not evaluated. 739 * 740 * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting 741 * terminal operation</a>. 742 * 743 * @apiNote 744 * This method evaluates the <em>existential quantification</em> of the 745 * predicate over the elements of the stream (for some x P(x)). 746 * 747 * @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>, 748 * <a href="package-summary.html#Statelessness">stateless</a> 749 * predicate to apply to elements of this stream 750 * @return {@code true} if any elements of the stream match the provided 751 * predicate, otherwise {@code false} 752 */ 753 boolean anyMatch(IntPredicate predicate); 754 755 /** 756 * Returns whether all elements of this stream match the provided predicate. 757 * May not evaluate the predicate on all elements if not necessary for 758 * determining the result. If the stream is empty then {@code true} is 759 * returned and the predicate is not evaluated. 760 * 761 * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting 762 * terminal operation</a>. 763 * 764 * @apiNote 765 * This method evaluates the <em>universal quantification</em> of the 766 * predicate over the elements of the stream (for all x P(x)). If the 767 * stream is empty, the quantification is said to be <em>vacuously 768 * satisfied</em> and is always {@code true} (regardless of P(x)). 769 * 770 * @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>, 771 * <a href="package-summary.html#Statelessness">stateless</a> 772 * predicate to apply to elements of this stream 773 * @return {@code true} if either all elements of the stream match the 774 * provided predicate or the stream is empty, otherwise {@code false} 775 */ 776 boolean allMatch(IntPredicate predicate); 777 778 /** 779 * Returns whether no elements of this stream match the provided predicate. 780 * May not evaluate the predicate on all elements if not necessary for 781 * determining the result. If the stream is empty then {@code true} is 782 * returned and the predicate is not evaluated. 783 * 784 * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting 785 * terminal operation</a>. 786 * 787 * @apiNote 788 * This method evaluates the <em>universal quantification</em> of the 789 * negated predicate over the elements of the stream (for all x ~P(x)). If 790 * the stream is empty, the quantification is said to be vacuously satisfied 791 * and is always {@code true}, regardless of P(x). 792 * 793 * @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>, 794 * <a href="package-summary.html#Statelessness">stateless</a> 795 * predicate to apply to elements of this stream 796 * @return {@code true} if either no elements of the stream match the 797 * provided predicate or the stream is empty, otherwise {@code false} 798 */ 799 boolean noneMatch(IntPredicate predicate); 800 801 /** 802 * Returns an {@link OptionalInt} describing the first element of this 803 * stream, or an empty {@code OptionalInt} if the stream is empty. If the 804 * stream has no encounter order, then any element may be returned. 805 * 806 * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting 807 * terminal operation</a>. 808 * 809 * @return an {@code OptionalInt} describing the first element of this stream, 810 * or an empty {@code OptionalInt} if the stream is empty 811 */ findFirst()812 OptionalInt findFirst(); 813 814 /** 815 * Returns an {@link OptionalInt} describing some element of the stream, or 816 * an empty {@code OptionalInt} if the stream is empty. 817 * 818 * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting 819 * terminal operation</a>. 820 * 821 * <p>The behavior of this operation is explicitly nondeterministic; it is 822 * free to select any element in the stream. This is to allow for maximal 823 * performance in parallel operations; the cost is that multiple invocations 824 * on the same source may not return the same result. (If a stable result 825 * is desired, use {@link #findFirst()} instead.) 826 * 827 * @return an {@code OptionalInt} describing some element of this stream, or 828 * an empty {@code OptionalInt} if the stream is empty 829 * @see #findFirst() 830 */ findAny()831 OptionalInt findAny(); 832 833 /** 834 * Returns a {@code LongStream} consisting of the elements of this stream, 835 * converted to {@code long}. 836 * 837 * <p>This is an <a href="package-summary.html#StreamOps">intermediate 838 * operation</a>. 839 * 840 * @return a {@code LongStream} consisting of the elements of this stream, 841 * converted to {@code long} 842 */ asLongStream()843 LongStream asLongStream(); 844 845 /** 846 * Returns a {@code DoubleStream} consisting of the elements of this stream, 847 * converted to {@code double}. 848 * 849 * <p>This is an <a href="package-summary.html#StreamOps">intermediate 850 * operation</a>. 851 * 852 * @return a {@code DoubleStream} consisting of the elements of this stream, 853 * converted to {@code double} 854 */ asDoubleStream()855 DoubleStream asDoubleStream(); 856 857 /** 858 * Returns a {@code Stream} consisting of the elements of this stream, 859 * each boxed to an {@code Integer}. 860 * 861 * <p>This is an <a href="package-summary.html#StreamOps">intermediate 862 * operation</a>. 863 * 864 * @return a {@code Stream} consistent of the elements of this stream, 865 * each boxed to an {@code Integer} 866 */ boxed()867 Stream<Integer> boxed(); 868 869 @Override sequential()870 IntStream sequential(); 871 872 @Override parallel()873 IntStream parallel(); 874 875 @Override iterator()876 PrimitiveIterator.OfInt iterator(); 877 878 @Override spliterator()879 Spliterator.OfInt spliterator(); 880 881 // Static factories 882 883 /** 884 * Returns a builder for an {@code IntStream}. 885 * 886 * @return a stream builder 887 */ builder()888 public static Builder builder() { 889 return new Streams.IntStreamBuilderImpl(); 890 } 891 892 /** 893 * Returns an empty sequential {@code IntStream}. 894 * 895 * @return an empty sequential stream 896 */ empty()897 public static IntStream empty() { 898 return StreamSupport.intStream(Spliterators.emptyIntSpliterator(), false); 899 } 900 901 /** 902 * Returns a sequential {@code IntStream} containing a single element. 903 * 904 * @param t the single element 905 * @return a singleton sequential stream 906 */ of(int t)907 public static IntStream of(int t) { 908 return StreamSupport.intStream(new Streams.IntStreamBuilderImpl(t), false); 909 } 910 911 /** 912 * Returns a sequential ordered stream whose elements are the specified values. 913 * 914 * @param values the elements of the new stream 915 * @return the new stream 916 */ of(int... values)917 public static IntStream of(int... values) { 918 return Arrays.stream(values); 919 } 920 921 /** 922 * Returns an infinite sequential ordered {@code IntStream} produced by iterative 923 * application of a function {@code f} to an initial element {@code seed}, 924 * producing a {@code Stream} consisting of {@code seed}, {@code f(seed)}, 925 * {@code f(f(seed))}, etc. 926 * 927 * <p>The first element (position {@code 0}) in the {@code IntStream} will be 928 * the provided {@code seed}. For {@code n > 0}, the element at position 929 * {@code n}, will be the result of applying the function {@code f} to the 930 * element at position {@code n - 1}. 931 * 932 * <p>The action of applying {@code f} for one element 933 * <a href="../concurrent/package-summary.html#MemoryVisibility"><i>happens-before</i></a> 934 * the action of applying {@code f} for subsequent elements. For any given 935 * element the action may be performed in whatever thread the library 936 * chooses. 937 * 938 * @param seed the initial element 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 */ iterate(final int seed, final IntUnaryOperator f)943 public static IntStream iterate(final int seed, final IntUnaryOperator f) { 944 Objects.requireNonNull(f); 945 Spliterator.OfInt spliterator = new Spliterators.AbstractIntSpliterator(Long.MAX_VALUE, 946 Spliterator.ORDERED | Spliterator.IMMUTABLE | Spliterator.NONNULL) { 947 int prev; 948 boolean started; 949 950 @Override 951 public boolean tryAdvance(IntConsumer action) { 952 Objects.requireNonNull(action); 953 int t; 954 if (started) 955 t = f.applyAsInt(prev); 956 else { 957 t = seed; 958 started = true; 959 } 960 action.accept(prev = t); 961 return true; 962 } 963 }; 964 return StreamSupport.intStream(spliterator, false); 965 } 966 967 /** 968 * Returns a sequential ordered {@code IntStream} produced by iterative 969 * application of the given {@code next} function to an initial element, 970 * conditioned on satisfying the given {@code hasNext} predicate. The 971 * stream terminates as soon as the {@code hasNext} predicate returns false. 972 * 973 * <p>{@code IntStream.iterate} should produce the same sequence of elements as 974 * produced by the corresponding for-loop: 975 * <pre>{@code 976 * for (int index=seed; hasNext.test(index); index = next.applyAsInt(index)) { 977 * ... 978 * } 979 * }</pre> 980 * 981 * <p>The resulting sequence may be empty if the {@code hasNext} predicate 982 * does not hold on the seed value. Otherwise the first element will be the 983 * supplied {@code seed} value, the next element (if present) will be the 984 * result of applying the {@code next} function to the {@code seed} value, 985 * and so on iteratively until the {@code hasNext} predicate indicates that 986 * the stream should terminate. 987 * 988 * <p>The action of applying the {@code hasNext} predicate to an element 989 * <a href="../concurrent/package-summary.html#MemoryVisibility"><i>happens-before</i></a> 990 * the action of applying the {@code next} function to that element. The 991 * action of applying the {@code next} function for one element 992 * <i>happens-before</i> the action of applying the {@code hasNext} 993 * predicate for subsequent elements. For any given element an action may 994 * be performed in whatever thread the library chooses. 995 * 996 * @param seed the initial element 997 * @param hasNext a predicate to apply to elements to determine when the 998 * stream must terminate. 999 * @param next a function to be applied to the previous element to produce 1000 * a new element 1001 * @return a new sequential {@code IntStream} 1002 * @since 9 1003 */ iterate(int seed, IntPredicate hasNext, IntUnaryOperator next)1004 public static IntStream iterate(int seed, IntPredicate hasNext, IntUnaryOperator next) { 1005 Objects.requireNonNull(next); 1006 Objects.requireNonNull(hasNext); 1007 Spliterator.OfInt spliterator = new Spliterators.AbstractIntSpliterator(Long.MAX_VALUE, 1008 Spliterator.ORDERED | Spliterator.IMMUTABLE | Spliterator.NONNULL) { 1009 int prev; 1010 boolean started, finished; 1011 1012 @Override 1013 public boolean tryAdvance(IntConsumer action) { 1014 Objects.requireNonNull(action); 1015 if (finished) 1016 return false; 1017 int t; 1018 if (started) 1019 t = next.applyAsInt(prev); 1020 else { 1021 t = seed; 1022 started = true; 1023 } 1024 if (!hasNext.test(t)) { 1025 finished = true; 1026 return false; 1027 } 1028 action.accept(prev = t); 1029 return true; 1030 } 1031 1032 @Override 1033 public void forEachRemaining(IntConsumer action) { 1034 Objects.requireNonNull(action); 1035 if (finished) 1036 return; 1037 finished = true; 1038 int t = started ? next.applyAsInt(prev) : seed; 1039 while (hasNext.test(t)) { 1040 action.accept(t); 1041 t = next.applyAsInt(t); 1042 } 1043 } 1044 }; 1045 return StreamSupport.intStream(spliterator, false); 1046 } 1047 1048 /** 1049 * Returns an infinite sequential unordered stream where each element is 1050 * generated by the provided {@code IntSupplier}. This is suitable for 1051 * generating constant streams, streams of random elements, etc. 1052 * 1053 * @param s the {@code IntSupplier} for generated elements 1054 * @return a new infinite sequential unordered {@code IntStream} 1055 */ generate(IntSupplier s)1056 public static IntStream generate(IntSupplier s) { 1057 Objects.requireNonNull(s); 1058 return StreamSupport.intStream( 1059 new StreamSpliterators.InfiniteSupplyingSpliterator.OfInt(Long.MAX_VALUE, s), false); 1060 } 1061 1062 /** 1063 * Returns a sequential ordered {@code IntStream} from {@code startInclusive} 1064 * (inclusive) to {@code endExclusive} (exclusive) by an incremental step of 1065 * {@code 1}. 1066 * 1067 * @apiNote 1068 * <p>An equivalent sequence of increasing values can be produced 1069 * sequentially using a {@code for} loop as follows: 1070 * <pre>{@code 1071 * for (int i = startInclusive; i < endExclusive ; i++) { ... } 1072 * }</pre> 1073 * 1074 * @param startInclusive the (inclusive) initial value 1075 * @param endExclusive the exclusive upper bound 1076 * @return a sequential {@code IntStream} for the range of {@code int} 1077 * elements 1078 */ range(int startInclusive, int endExclusive)1079 public static IntStream range(int startInclusive, int endExclusive) { 1080 if (startInclusive >= endExclusive) { 1081 return empty(); 1082 } else { 1083 return StreamSupport.intStream( 1084 new Streams.RangeIntSpliterator(startInclusive, endExclusive, false), false); 1085 } 1086 } 1087 1088 /** 1089 * Returns a sequential ordered {@code IntStream} from {@code startInclusive} 1090 * (inclusive) to {@code endInclusive} (inclusive) by an incremental step of 1091 * {@code 1}. 1092 * 1093 * @apiNote 1094 * <p>An equivalent sequence of increasing values can be produced 1095 * sequentially using a {@code for} loop as follows: 1096 * <pre>{@code 1097 * for (int i = startInclusive; i <= endInclusive ; i++) { ... } 1098 * }</pre> 1099 * 1100 * @param startInclusive the (inclusive) initial value 1101 * @param endInclusive the inclusive upper bound 1102 * @return a sequential {@code IntStream} for the range of {@code int} 1103 * elements 1104 */ rangeClosed(int startInclusive, int endInclusive)1105 public static IntStream rangeClosed(int startInclusive, int endInclusive) { 1106 if (startInclusive > endInclusive) { 1107 return empty(); 1108 } else { 1109 return StreamSupport.intStream( 1110 new Streams.RangeIntSpliterator(startInclusive, endInclusive, true), false); 1111 } 1112 } 1113 1114 /** 1115 * Creates a lazily concatenated stream whose elements are all the 1116 * elements of the first stream followed by all the elements of the 1117 * second stream. The resulting stream is ordered if both 1118 * of the input streams are ordered, and parallel if either of the input 1119 * streams is parallel. When the resulting stream is closed, the close 1120 * handlers for both input streams are invoked. 1121 * 1122 * <p>This method operates on the two input streams and binds each stream 1123 * to its source. As a result subsequent modifications to an input stream 1124 * source may not be reflected in the concatenated stream result. 1125 * 1126 * @implNote 1127 * Use caution when constructing streams from repeated concatenation. 1128 * Accessing an element of a deeply concatenated stream can result in deep 1129 * call chains, or even {@code StackOverflowError}. 1130 * 1131 * @apiNote 1132 * To preserve optimization opportunities this method binds each stream to 1133 * its source and accepts only two streams as parameters. For example, the 1134 * exact size of the concatenated stream source can be computed if the exact 1135 * size of each input stream source is known. 1136 * To concatenate more streams without binding, or without nested calls to 1137 * this method, try creating a stream of streams and flat-mapping with the 1138 * identity function, for example: 1139 * <pre>{@code 1140 * IntStream concat = Stream.of(s1, s2, s3, s4).flatMapToInt(s -> s); 1141 * }</pre> 1142 * 1143 * @param a the first stream 1144 * @param b the second stream 1145 * @return the concatenation of the two input streams 1146 */ concat(IntStream a, IntStream b)1147 public static IntStream concat(IntStream a, IntStream b) { 1148 Objects.requireNonNull(a); 1149 Objects.requireNonNull(b); 1150 1151 Spliterator.OfInt split = new Streams.ConcatSpliterator.OfInt( 1152 a.spliterator(), b.spliterator()); 1153 IntStream stream = StreamSupport.intStream(split, a.isParallel() || b.isParallel()); 1154 return stream.onClose(Streams.composedClose(a, b)); 1155 } 1156 1157 /** 1158 * A mutable builder for an {@code IntStream}. 1159 * 1160 * <p>A stream builder has a lifecycle, which starts in a building 1161 * phase, during which elements can be added, and then transitions to a built 1162 * phase, after which elements may not be added. The built phase 1163 * begins when the {@link #build()} method is called, which creates an 1164 * ordered stream whose elements are the elements that were added to the 1165 * stream builder, in the order they were added. 1166 * 1167 * @see IntStream#builder() 1168 * @since 1.8 1169 */ 1170 public interface Builder extends IntConsumer { 1171 1172 /** 1173 * Adds an element to the stream being built. 1174 * 1175 * @throws IllegalStateException if the builder has already transitioned 1176 * to the built state 1177 */ 1178 @Override accept(int t)1179 void accept(int t); 1180 1181 /** 1182 * Adds an element to the stream being built. 1183 * 1184 * @implSpec 1185 * The default implementation behaves as if: 1186 * <pre>{@code 1187 * accept(t) 1188 * return this; 1189 * }</pre> 1190 * 1191 * @param t the element to add 1192 * @return {@code this} builder 1193 * @throws IllegalStateException if the builder has already transitioned 1194 * to the built state 1195 */ add(int t)1196 default Builder add(int t) { 1197 accept(t); 1198 return this; 1199 } 1200 1201 /** 1202 * Builds the stream, transitioning this builder to the built state. 1203 * An {@code IllegalStateException} is thrown if there are further 1204 * attempts to operate on the builder after it has entered the built 1205 * state. 1206 * 1207 * @return the built stream 1208 * @throws IllegalStateException if the builder has already transitioned to 1209 * the built state 1210 */ build()1211 IntStream build(); 1212 } 1213 1214 /** 1215 * Represents an operation that accepts an {@code int}-valued argument 1216 * and an IntConsumer, and returns no result. This functional interface is 1217 * used by {@link IntStream#mapMulti(IntMapMultiConsumer) IntStream.mapMulti} 1218 * to replace an int value with zero or more int values. 1219 * 1220 * <p>This is a <a href="../function/package-summary.html">functional interface</a> 1221 * whose functional method is {@link #accept(int, IntConsumer)}. 1222 * 1223 * @see IntStream#mapMulti(IntMapMultiConsumer) 1224 * 1225 * @since 16 1226 */ 1227 @FunctionalInterface 1228 interface IntMapMultiConsumer { 1229 1230 /** 1231 * Replaces the given {@code value} with zero or more values by feeding the mapped 1232 * values to the {@code ic} consumer. 1233 * 1234 * @param value the int value coming from upstream 1235 * @param ic an {@code IntConsumer} accepting the mapped values 1236 */ accept(int value, IntConsumer ic)1237 void accept(int value, IntConsumer ic); 1238 } 1239 } 1240