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