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.util.Arrays; 28 import java.util.Comparator; 29 import java.util.Iterator; 30 import java.util.Objects; 31 import java.util.Optional; 32 import java.util.Spliterator; 33 import java.util.Spliterators; 34 import java.util.function.BiConsumer; 35 import java.util.function.BiFunction; 36 import java.util.function.BinaryOperator; 37 import java.util.function.Consumer; 38 import java.util.function.Function; 39 import java.util.function.IntFunction; 40 import java.util.function.Predicate; 41 import java.util.function.Supplier; 42 import java.util.function.ToDoubleFunction; 43 import java.util.function.ToIntFunction; 44 import java.util.function.ToLongFunction; 45 import java.util.function.UnaryOperator; 46 47 // @@@ Specification to-do list @@@ 48 // - Describe the difference between sequential and parallel streams 49 // - More general information about reduce, better definitions for associativity, more description of 50 // how reduce employs parallelism, more examples 51 // - Role of stream flags in various operations, specifically ordering 52 // - Whether each op preserves encounter order 53 // @@@ Specification to-do list @@@ 54 55 /** 56 * A sequence of elements supporting sequential and parallel bulk operations. 57 * Streams support lazy intermediate operations (transforming a stream to 58 * another stream) such as {@code filter} and {@code map}, and terminal 59 * operations (consuming the contents of a stream to produce a result or 60 * side-effect), such as {@code forEach}, {@code findFirst}, and {@code 61 * iterator}. Once an operation has been performed on a stream, it 62 * is considered <em>consumed</em> and no longer usable for other operations. 63 * 64 * <p>For sequential stream pipelines, all operations are performed in the 65 * <a href="package-summary.html#Ordering">encounter order</a> of the pipeline 66 * source, if the pipeline source has a defined encounter order. 67 * 68 * <p>For parallel stream pipelines, unless otherwise specified, intermediate 69 * stream operations preserve the <a href="package-summary.html#Ordering"> 70 * encounter order</a> of their source, and terminal operations 71 * respect the encounter order of their source, if the source 72 * has an encounter order. Provided that and parameters to stream operations 73 * satisfy the <a href="package-summary.html#NonInterference">non-interference 74 * requirements</a>, and excepting differences arising from the absence of 75 * a defined encounter order, the result of a stream pipeline should be the 76 * stable across multiple executions of the same operations on the same source. 77 * However, the timing and thread in which side-effects occur (for those 78 * operations which are allowed to produce side-effects, such as 79 * {@link #forEach(Consumer)}), are explicitly nondeterministic for parallel 80 * execution of stream pipelines. 81 * 82 * <p>Unless otherwise noted, passing a {@code null} argument to any stream 83 * method may result in a {@link NullPointerException}. 84 * 85 * @apiNote 86 * Streams are not data structures; they do not manage the storage for their 87 * elements, nor do they support access to individual elements. However, 88 * you can use the {@link #iterator()} or {@link #spliterator()} operations to 89 * perform a controlled traversal. 90 * 91 * @param <T> type of elements 92 * @since 1.8 93 * @see <a href="package-summary.html">java.util.stream</a> 94 */ 95 public interface Stream<T> extends BaseStream<T, Stream<T>> { 96 97 /** 98 * Returns a stream consisting of the elements of this stream that match 99 * the given predicate. 100 * 101 * <p>This is an <a href="package-summary.html#StreamOps">intermediate 102 * operation</a>. 103 * 104 * @param predicate a <a href="package-summary.html#NonInterference"> 105 * non-interfering, stateless</a> predicate to apply to 106 * each element to determine if it should be included 107 * @return the new stream 108 */ 109 Stream<T> filter(Predicate<? super T> predicate); 110 111 /** 112 * Returns a stream consisting of the results of applying the given 113 * function to the elements of this stream. 114 * 115 * <p>This is an <a href="package-summary.html#StreamOps">intermediate 116 * operation</a>. 117 * 118 * @param <R> The element type of the new stream 119 * @param mapper a <a href="package-summary.html#NonInterference"> 120 * non-interfering, stateless</a> function to apply to each 121 * element 122 * @return the new stream 123 */ 124 <R> Stream<R> map(Function<? super T, ? extends R> mapper); 125 126 /** 127 * Returns an {@code IntStream} consisting of the results of applying the 128 * given function to the elements of this stream. 129 * 130 * <p>This is an <a href="package-summary.html#StreamOps"> 131 * intermediate operation</a>. 132 * 133 * @param mapper a <a href="package-summary.html#NonInterference"> 134 * non-interfering, stateless</a> function to apply to each 135 * element 136 * @return the new stream 137 */ 138 IntStream mapToInt(ToIntFunction<? super T> mapper); 139 140 /** 141 * Returns a {@code LongStream} consisting of the results of applying the 142 * given function to the elements of this stream. 143 * 144 * <p>This is an <a href="package-summary.html#StreamOps">intermediate 145 * operation</a>. 146 * 147 * @param mapper a <a href="package-summary.html#NonInterference"> 148 * non-interfering, stateless</a> function to apply to each 149 * element 150 * @return the new stream 151 */ 152 LongStream mapToLong(ToLongFunction<? super T> mapper); 153 154 /** 155 * Returns a {@code DoubleStream} consisting of the results of applying the 156 * given function to the elements of this stream. 157 * 158 * <p>This is an <a href="package-summary.html#StreamOps">intermediate 159 * operation</a>. 160 * 161 * @param mapper a <a href="package-summary.html#NonInterference"> 162 * non-interfering, stateless</a> function to apply to each 163 * element 164 * @return the new stream 165 */ 166 DoubleStream mapToDouble(ToDoubleFunction<? super T> mapper); 167 168 /** 169 * Returns a stream consisting of the results of replacing each element of 170 * this stream with the contents of the stream produced by applying the 171 * provided mapping function to each element. If the result of the mapping 172 * function is {@code null}, this is treated as if the result is an empty 173 * stream. 174 * 175 * <p>This is an <a href="package-summary.html#StreamOps">intermediate 176 * operation</a>. 177 * 178 * @apiNote 179 * The {@code flatMap()} operation has the effect of applying a one-to-many 180 * tranformation to the elements of the stream, and then flattening the 181 * resulting elements into a new stream. For example, if {@code orders} 182 * is a stream of purchase orders, and each purchase order contains a 183 * collection of line items, then the following produces a stream of line 184 * items: 185 * <pre>{@code 186 * orderStream.flatMap(order -> order.getLineItems().stream())... 187 * }</pre> 188 * 189 * @param <R> The element type of the new stream 190 * @param mapper a <a href="package-summary.html#NonInterference"> 191 * non-interfering, stateless</a> function to apply to each 192 * element which produces a stream of new values 193 * @return the new stream 194 */ 195 <R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper); 196 197 /** 198 * Returns an {@code IntStream} consisting of the results of replacing each 199 * element of this stream with the contents of the stream produced by 200 * applying the provided mapping function to each element. If the result of 201 * the mapping function is {@code null}, this is treated as if the result is 202 * an empty stream. 203 * 204 * <p>This is an <a href="package-summary.html#StreamOps">intermediate 205 * operation</a>. 206 * 207 * @param mapper a <a href="package-summary.html#NonInterference"> 208 * non-interfering, stateless</a> function to apply to each 209 * element which produces a stream of new values 210 * @return the new stream 211 */ 212 IntStream flatMapToInt(Function<? super T, ? extends IntStream> mapper); 213 214 /** 215 * Returns a {@code LongStream} consisting of the results of replacing each 216 * element of this stream with the contents of the stream produced 217 * by applying the provided mapping function to each element. If the result 218 * of the mapping function is {@code null}, this is treated as if the 219 * result is an empty stream. 220 * 221 * <p>This is an <a href="package-summary.html#StreamOps">intermediate 222 * operation</a>. 223 * 224 * @param mapper a <a href="package-summary.html#NonInterference"> 225 * non-interfering, stateless</a> function to apply to 226 * each element which produces a stream of new values 227 * @return the new stream 228 */ 229 LongStream flatMapToLong(Function<? super T, ? extends LongStream> mapper); 230 231 /** 232 * Returns a {@code DoubleStream} consisting of the results of replacing each 233 * element of this stream with the contents of the stream produced 234 * by applying the provided mapping function to each element. If the result 235 * of the mapping function is {@code null}, this is treated as if the result 236 * is an empty stream. 237 * 238 * <p>This is an <a href="package-summary.html#StreamOps">intermediate 239 * operation</a>. 240 * 241 * @param mapper a <a href="package-summary.html#NonInterference"> 242 * non-interfering, stateless</a> function to apply to each 243 * element which produces a stream of new values 244 * @return the new stream 245 */ 246 DoubleStream flatMapToDouble(Function<? super T, ? extends DoubleStream> mapper); 247 248 /** 249 * Returns a stream consisting of the distinct elements (according to 250 * {@link Object#equals(Object)}) of this stream. 251 * 252 * <p>This is a <a href="package-summary.html#StreamOps">stateful 253 * intermediate operation</a>. 254 * 255 * @return the new stream 256 */ 257 Stream<T> distinct(); 258 259 /** 260 * Returns a stream consisting of the elements of this stream, sorted 261 * according to natural order. If the elements of this stream are not 262 * {@code Comparable}, a {@code java.lang.ClassCastException} may be thrown 263 * when the stream pipeline is executed. 264 * 265 * <p>This is a <a href="package-summary.html#StreamOps">stateful 266 * intermediate operation</a>. 267 * 268 * @return the new stream 269 */ 270 Stream<T> sorted(); 271 272 /** 273 * Returns a stream consisting of the elements of this stream, sorted 274 * according to the provided {@code Comparator}. 275 * 276 * <p>This is a <a href="package-summary.html#StreamOps">stateful 277 * intermediate operation</a>. 278 * 279 * @param comparator a <a href="package-summary.html#NonInterference"> 280 * non-interfering, stateless</a> {@code Comparator} to 281 * be used to compare stream elements 282 * @return the new stream 283 */ 284 Stream<T> sorted(Comparator<? super T> comparator); 285 286 /** 287 * Returns a stream consisting of the elements of this stream, additionally 288 * performing the provided action on each element as elements are consumed 289 * from the resulting stream. 290 * 291 * <p>This is an <a href="package-summary.html#StreamOps">intermediate 292 * operation</a>. 293 * 294 * <p>For parallel stream pipelines, the action may be called at 295 * whatever time and in whatever thread the element is made available by the 296 * upstream operation. If the action modifies shared state, 297 * it is responsible for providing the required synchronization. 298 * 299 * @apiNote This method exists mainly to support debugging, where you want 300 * to see the elements as they flow past a certain point in a pipeline: 301 * <pre>{@code 302 * list.stream() 303 * .filter(filteringFunction) 304 * .peek(e -> {System.out.println("Filtered value: " + e); }); 305 * .map(mappingFunction) 306 * .peek(e -> {System.out.println("Mapped value: " + e); }); 307 * .collect(Collectors.intoList()); 308 * }</pre> 309 * 310 * @param consumer a <a href="package-summary.html#NonInterference"> 311 * non-interfering</a> action to perform on the elements as 312 * they are consumed from the stream 313 * @return the new stream 314 */ 315 Stream<T> peek(Consumer<? super T> consumer); 316 317 /** 318 * Returns a stream consisting of the elements of this stream, truncated 319 * to be no longer than {@code maxSize} in length. 320 * 321 * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting 322 * stateful intermediate operation</a>. 323 * 324 * @param maxSize the number of elements the stream should be limited to 325 * @return the new stream 326 * @throws IllegalArgumentException if {@code maxSize} is negative 327 */ 328 Stream<T> limit(long maxSize); 329 330 /** 331 * Returns a stream consisting of the remaining elements of this stream 332 * after indexing {@code startInclusive} elements into the stream. If the 333 * {@code startInclusive} index lies past the end of this stream then an 334 * empty stream will be returned. 335 * 336 * <p>This is a <a href="package-summary.html#StreamOps">stateful 337 * intermediate operation</a>. 338 * 339 * @param startInclusive the number of leading elements to skip 340 * @return the new stream 341 * @throws IllegalArgumentException if {@code startInclusive} is negative 342 */ 343 Stream<T> substream(long startInclusive); 344 345 /** 346 * Returns a stream consisting of the remaining elements of this stream 347 * after indexing {@code startInclusive} elements into the stream and 348 * truncated to contain no more than {@code endExclusive - startInclusive} 349 * elements. If the {@code startInclusive} index lies past the end 350 * of this stream then an empty stream will be returned. 351 * 352 * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting 353 * stateful intermediate operation</a>. 354 * 355 * @param startInclusive the starting position of the substream, inclusive 356 * @param endExclusive the ending position of the substream, exclusive 357 * @return the new stream 358 * @throws IllegalArgumentException if {@code startInclusive} or 359 * {@code endExclusive} is negative or {@code startInclusive} is greater 360 * than {@code endExclusive} 361 */ 362 Stream<T> substream(long startInclusive, long endExclusive); 363 364 /** 365 * Performs an action for each element of this stream. 366 * 367 * <p>This is a <a href="package-summary.html#StreamOps">terminal 368 * operation</a>. 369 * 370 * <p>For parallel stream pipelines, this operation does <em>not</em> 371 * guarantee to respect the encounter order of the stream, as doing so 372 * would sacrifice the benefit of parallelism. For any given element, the 373 * action may be performed at whatever time and in whatever thread the 374 * library chooses. If the action accesses shared state, it is 375 * responsible for providing the required synchronization. 376 * 377 * @param action a <a href="package-summary.html#NonInterference"> 378 * non-interfering</a> action to perform on the elements 379 */ 380 void forEach(Consumer<? super T> action); 381 382 /** 383 * Performs an action for each element of this stream, guaranteeing that 384 * each element is processed in encounter order for streams that have a 385 * defined encounter order. 386 * 387 * <p>This is a <a href="package-summary.html#StreamOps">terminal 388 * operation</a>. 389 * 390 * @param action a <a href="package-summary.html#NonInterference"> 391 * non-interfering</a> action to perform on the elements 392 * @see #forEach(Consumer) 393 */ 394 void forEachOrdered(Consumer<? super T> action); 395 396 /** 397 * Returns an array containing the elements of this stream. 398 * 399 * <p>This is a <a href="package-summary.html#StreamOps">terminal 400 * operation</a>. 401 * 402 * @return an array containing the elements of this stream 403 */ 404 Object[] toArray(); 405 406 /** 407 * Returns an array containing the elements of this stream, using the 408 * provided {@code generator} function to allocate the returned array. 409 * 410 * <p>This is a <a href="package-summary.html#StreamOps">terminal 411 * operation</a>. 412 * 413 * @param <A> the element type of the resulting array 414 * @param generator a function which produces a new array of the desired 415 * type and the provided length 416 * @return an array containing the elements in this stream 417 * @throws ArrayStoreException if the runtime type of the array returned 418 * from the array generator is not a supertype of the runtime type of every 419 * element in this stream 420 */ 421 <A> A[] toArray(IntFunction<A[]> generator); 422 423 /** 424 * Performs a <a href="package-summary.html#Reduction">reduction</a> on the 425 * elements of this stream, using the provided identity value and an 426 * <a href="package-summary.html#Associativity">associative</a> 427 * accumulation function, and returns the reduced value. This is equivalent 428 * to: 429 * <pre>{@code 430 * T result = identity; 431 * for (T element : this stream) 432 * result = accumulator.apply(result, element) 433 * return result; 434 * }</pre> 435 * 436 * but is not constrained to execute sequentially. 437 * 438 * <p>The {@code identity} value must be an identity for the accumulator 439 * function. This means that for all {@code t}, 440 * {@code accumulator.apply(identity, t)} is equal to {@code t}. 441 * The {@code accumulator} function must be an 442 * <a href="package-summary.html#Associativity">associative</a> function. 443 * 444 * <p>This is a <a href="package-summary.html#StreamOps">terminal 445 * operation</a>. 446 * 447 * @apiNote Sum, min, max, average, and string concatenation are all special 448 * cases of reduction. Summing a stream of numbers can be expressed as: 449 * 450 * <pre>{@code 451 * Integer sum = integers.reduce(0, (a, b) -> a+b); 452 * }</pre> 453 * 454 * or more compactly: 455 * 456 * <pre>{@code 457 * Integer sum = integers.reduce(0, Integer::sum); 458 * }</pre> 459 * 460 * <p>While this may seem a more roundabout way to perform an aggregation 461 * compared to simply mutating a running total in a loop, reduction 462 * operations parallelize more gracefully, without needing additional 463 * synchronization and with greatly reduced risk of data races. 464 * 465 * @param identity the identity value for the accumulating function 466 * @param accumulator an <a href="package-summary.html#Associativity">associative</a> 467 * <a href="package-summary.html#NonInterference">non-interfering, 468 * stateless</a> function for combining two values 469 * @return the result of the reduction 470 */ 471 T reduce(T identity, BinaryOperator<T> accumulator); 472 473 /** 474 * Performs a <a href="package-summary.html#Reduction">reduction</a> on the 475 * elements of this stream, using an 476 * <a href="package-summary.html#Associativity">associative</a> accumulation 477 * function, and returns an {@code Optional} describing the reduced value, 478 * if any. This is equivalent to: 479 * <pre>{@code 480 * boolean foundAny = false; 481 * T result = null; 482 * for (T element : this stream) { 483 * if (!foundAny) { 484 * foundAny = true; 485 * result = element; 486 * } 487 * else 488 * result = accumulator.apply(result, element); 489 * } 490 * return foundAny ? Optional.of(result) : Optional.empty(); 491 * }</pre> 492 * 493 * but is not constrained to execute sequentially. 494 * 495 * <p>The {@code accumulator} function must be an 496 * <a href="package-summary.html#Associativity">associative</a> function. 497 * 498 * <p>This is a <a href="package-summary.html#StreamOps">terminal 499 * operation</a>. 500 * 501 * @param accumulator an <a href="package-summary.html#Associativity">associative</a> 502 * <a href="package-summary.html#NonInterference">non-interfering, 503 * stateless</a> function for combining two values 504 * @return the result of the reduction 505 * @see #reduce(Object, BinaryOperator) 506 * @see #min(java.util.Comparator) 507 * @see #max(java.util.Comparator) 508 */ 509 Optional<T> reduce(BinaryOperator<T> accumulator); 510 511 /** 512 * Performs a <a href="package-summary.html#Reduction">reduction</a> on the 513 * elements of this stream, using the provided identity, accumulation 514 * function, and a combining functions. This is equivalent to: 515 * <pre>{@code 516 * U result = identity; 517 * for (T element : this stream) 518 * result = accumulator.apply(result, element) 519 * return result; 520 * }</pre> 521 * 522 * but is not constrained to execute sequentially. 523 * 524 * <p>The {@code identity} value must be an identity for the combiner 525 * function. This means that for all {@code u}, {@code combiner(identity, u)} 526 * is equal to {@code u}. Additionally, the {@code combiner} function 527 * must be compatible with the {@code accumulator} function; for all 528 * {@code u} and {@code t}, the following must hold: 529 * <pre>{@code 530 * combiner.apply(u, accumulator.apply(identity, t)) == accumulator.apply(u, t) 531 * }</pre> 532 * 533 * <p>This is a <a href="package-summary.html#StreamOps">terminal 534 * operation</a>. 535 * 536 * @apiNote Many reductions using this form can be represented more simply 537 * by an explicit combination of {@code map} and {@code reduce} operations. 538 * The {@code accumulator} function acts as a fused mapper and accumulator, 539 * which can sometimes be more efficient than separate mapping and reduction, 540 * such as in the case where knowing the previously reduced value allows you 541 * to avoid some computation. 542 * 543 * @param <U> The type of the result 544 * @param identity the identity value for the combiner function 545 * @param accumulator an <a href="package-summary.html#Associativity">associative</a> 546 * <a href="package-summary.html#NonInterference">non-interfering, 547 * stateless</a> function for incorporating an additional 548 * element into a result 549 * @param combiner an <a href="package-summary.html#Associativity">associative</a> 550 * <a href="package-summary.html#NonInterference">non-interfering, 551 * stateless</a> function for combining two values, which 552 * must be compatible with the accumulator function 553 * @return the result of the reduction 554 * @see #reduce(BinaryOperator) 555 * @see #reduce(Object, BinaryOperator) 556 */ 557 <U> U reduce(U identity, 558 BiFunction<U, ? super T, U> accumulator, 559 BinaryOperator<U> combiner); 560 561 /** 562 * Performs a <a href="package-summary.html#MutableReduction">mutable 563 * reduction</a> operation on the elements of this stream. A mutable 564 * reduction is one in which the reduced value is a mutable value holder, 565 * such as an {@code ArrayList}, and elements are incorporated by updating 566 * the state of the result, rather than by replacing the result. This 567 * produces a result equivalent to: 568 * <pre>{@code 569 * R result = resultFactory.get(); 570 * for (T element : this stream) 571 * accumulator.accept(result, element); 572 * return result; 573 * }</pre> 574 * 575 * <p>Like {@link #reduce(Object, BinaryOperator)}, {@code collect} operations 576 * can be parallelized without requiring additional synchronization. 577 * 578 * <p>This is a <a href="package-summary.html#StreamOps">terminal 579 * operation</a>. 580 * 581 * @apiNote There are many existing classes in the JDK whose signatures are 582 * a good match for use as arguments to {@code collect()}. For example, 583 * the following will accumulate strings into an ArrayList: 584 * <pre>{@code 585 * List<String> asList = stringStream.collect(ArrayList::new, ArrayList::add, ArrayList::addAll); 586 * }</pre> 587 * 588 * <p>The following will take a stream of strings and concatenates them into a 589 * single string: 590 * <pre>{@code 591 * String concat = stringStream.collect(StringBuilder::new, StringBuilder::append, 592 * StringBuilder::append) 593 * .toString(); 594 * }</pre> 595 * 596 * @param <R> type of the result 597 * @param resultFactory a function that creates a new result container. 598 * For a parallel execution, this function may be 599 * called multiple times and must return a fresh value 600 * each time. 601 * @param accumulator an <a href="package-summary.html#Associativity">associative</a> 602 * <a href="package-summary.html#NonInterference">non-interfering, 603 * stateless</a> function for incorporating an additional 604 * element into a result 605 * @param combiner an <a href="package-summary.html#Associativity">associative</a> 606 * <a href="package-summary.html#NonInterference">non-interfering, 607 * stateless</a> function for combining two values, which 608 * must be compatible with the accumulator function 609 * @return the result of the reduction 610 */ 611 <R> R collect(Supplier<R> resultFactory, 612 BiConsumer<R, ? super T> accumulator, 613 BiConsumer<R, R> combiner); 614 615 /** 616 * Performs a <a href="package-summary.html#MutableReduction">mutable 617 * reduction</a> operation on the elements of this stream using a 618 * {@code Collector} object to describe the reduction. A {@code Collector} 619 * encapsulates the functions used as arguments to 620 * {@link #collect(Supplier, BiConsumer, BiConsumer)}, allowing for reuse of 621 * collection strategies, and composition of collect operations such as 622 * multiple-level grouping or partitioning. 623 * 624 * <p>This is a <a href="package-summary.html#StreamOps">terminal 625 * operation</a>. 626 * 627 * <p>When executed in parallel, multiple intermediate results may be 628 * instantiated, populated, and merged, so as to maintain isolation of 629 * mutable data structures. Therefore, even when executed in parallel 630 * with non-thread-safe data structures (such as {@code ArrayList}), no 631 * additional synchronization is needed for a parallel reduction. 632 * 633 * @apiNote 634 * The following will accumulate strings into an ArrayList: 635 * <pre>{@code 636 * List<String> asList = stringStream.collect(Collectors.toList()); 637 * }</pre> 638 * 639 * <p>The following will classify {@code Person} objects by city: 640 * <pre>{@code 641 * Map<String, Collection<Person>> peopleByCity 642 * = personStream.collect(Collectors.groupBy(Person::getCity)); 643 * }</pre> 644 * 645 * <p>The following will classify {@code Person} objects by state and city, 646 * cascading two {@code Collector}s together: 647 * <pre>{@code 648 * Map<String, Map<String, Collection<Person>>> peopleByStateAndCity 649 * = personStream.collect(Collectors.groupBy(Person::getState, 650 * Collectors.groupBy(Person::getCity))); 651 * }</pre> 652 * 653 * @param <R> the type of the result 654 * @param collector the {@code Collector} describing the reduction 655 * @return the result of the reduction 656 * @see #collect(Supplier, BiConsumer, BiConsumer) 657 * @see Collectors 658 */ 659 <R> R collect(Collector<? super T, R> collector); 660 661 /** 662 * Returns the minimum element of this stream according to the provided 663 * {@code Comparator}. This is a special case of a 664 * <a href="package-summary.html#MutableReduction">reduction</a>. 665 * 666 * <p>This is a <a href="package-summary.html#StreamOps">terminal operation</a>. 667 * 668 * @param comparator a <a href="package-summary.html#NonInterference">non-interfering, 669 * stateless</a> {@code Comparator} to use to compare 670 * elements of this stream 671 * @return an {@code Optional} describing the minimum element of this stream, 672 * or an empty {@code Optional} if the stream is empty 673 */ 674 Optional<T> min(Comparator<? super T> comparator); 675 676 /** 677 * Returns the maximum element of this stream according to the provided 678 * {@code Comparator}. This is a special case of a 679 * <a href="package-summary.html#MutableReduction">reduction</a>. 680 * 681 * <p>This is a <a href="package-summary.html#StreamOps">terminal 682 * operation</a>. 683 * 684 * @param comparator a <a href="package-summary.html#NonInterference">non-interfering, 685 * stateless</a> {@code Comparator} to use to compare 686 * elements of this stream 687 * @return an {@code Optional} describing the maximum element of this stream, 688 * or an empty {@code Optional} if the stream is empty 689 */ 690 Optional<T> max(Comparator<? super T> comparator); 691 692 /** 693 * Returns the count of elements in this stream. This is a special case of 694 * a <a href="package-summary.html#MutableReduction">reduction</a> and is 695 * equivalent to: 696 * <pre>{@code 697 * return mapToLong(e -> 1L).sum(); 698 * }</pre> 699 * 700 * <p>This is a <a href="package-summary.html#StreamOps">terminal operation</a>. 701 * 702 * @return the count of elements in this stream 703 */ 704 long count(); 705 706 /** 707 * Returns whether any elements of this stream match the provided 708 * predicate. May not evaluate the predicate on all elements if not 709 * necessary for determining the result. 710 * 711 * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting 712 * terminal operation</a>. 713 * 714 * @param predicate a <a href="package-summary.html#NonInterference">non-interfering, 715 * stateless</a> predicate to apply to elements of this 716 * stream 717 * @return {@code true} if any elements of the stream match the provided 718 * predicate otherwise {@code false} 719 */ 720 boolean anyMatch(Predicate<? super T> predicate); 721 722 /** 723 * Returns whether all elements of this stream match the provided predicate. 724 * May not evaluate the predicate on all elements if not necessary for 725 * determining the result. 726 * 727 * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting 728 * terminal operation</a>. 729 * 730 * @param predicate a <a href="package-summary.html#NonInterference">non-interfering, 731 * stateless</a> predicate to apply to elements of this 732 * stream 733 * @return {@code true} if all elements of the stream match the provided 734 * predicate otherwise {@code false} 735 */ 736 boolean allMatch(Predicate<? super T> predicate); 737 738 /** 739 * Returns whether no elements of this stream match the provided predicate. 740 * May not evaluate the predicate on all elements if not necessary for 741 * determining the result. 742 * 743 * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting 744 * terminal operation</a>. 745 * 746 * @param predicate a <a href="package-summary.html#NonInterference">non-interfering, 747 * stateless</a> predicate to apply to elements of this 748 * stream 749 * @return {@code true} if no elements of the stream match the provided 750 * predicate otherwise {@code false} 751 */ 752 boolean noneMatch(Predicate<? super T> predicate); 753 754 /** 755 * Returns an {@link Optional} describing the first element of this stream 756 * (in the encounter order), or an empty {@code Optional} if the stream is 757 * empty. If the stream has no encounter order, then any element may be 758 * returned. 759 * 760 * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting 761 * terminal operation</a>. 762 * 763 * @return an {@code Optional} describing the first element of this stream, 764 * or an empty {@code Optional} if the stream is empty 765 * @throws NullPointerException if the element selected is null 766 */ 767 Optional<T> findFirst(); 768 769 /** 770 * Returns an {@link Optional} describing some element of the stream, or an 771 * empty {@code Optional} if the stream is empty. 772 * 773 * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting 774 * terminal operation</a>. 775 * 776 * <p>The behavior of this operation is explicitly nondeterministic; it is 777 * free to select any element in the stream. This is to allow for maximal 778 * performance in parallel operations; the cost is that multiple invocations 779 * on the same source may not return the same result. (If the first element 780 * in the encounter order is desired, use {@link #findFirst()} instead.) 781 * 782 * @return an {@code Optional} describing some element of this stream, or an 783 * empty {@code Optional} if the stream is empty 784 * @throws NullPointerException if the element selected is null 785 * @see #findFirst() 786 */ 787 Optional<T> findAny(); 788 789 // Static factories 790 791 /** 792 * Returns a builder for a {@code Stream}. 793 * 794 * @param <T> type of elements 795 * @return a stream builder 796 */ 797 public static<T> Builder<T> builder() { 798 return new Streams.StreamBuilderImpl<>(); 799 } 800 801 /** 802 * Returns an empty sequential {@code Stream}. 803 * 804 * @param <T> the type of stream elements 805 * @return an empty sequential stream 806 */ 807 public static<T> Stream<T> empty() { 808 return StreamSupport.stream(Spliterators.<T>emptySpliterator(), false); 809 } 810 811 /** 812 * Returns a sequential {@code Stream} containing a single element. 813 * 814 * @param t the single element 815 * @param <T> the type of stream elements 816 * @return a singleton sequential stream 817 */ 818 public static<T> Stream<T> of(T t) { 819 return StreamSupport.stream(new Streams.StreamBuilderImpl<>(t), false); 820 } 821 822 /** 823 * Returns a sequential stream whose elements are the specified values. 824 * 825 * @param <T> the type of stream elements 826 * @param values the elements of the new stream 827 * @return the new stream 828 */ 829 @SafeVarargs 830 @SuppressWarnings("varargs") // Creating a stream for an array is safe 831 public static<T> Stream<T> of(T... values) { 832 return Arrays.stream(values); 833 } 834 835 /** 836 * Returns an infinite sequential {@code Stream} produced by iterative 837 * application of a function {@code f} to an initial element {@code seed}, 838 * producing a {@code Stream} consisting of {@code seed}, {@code f(seed)}, 839 * {@code f(f(seed))}, etc. 840 * 841 * <p>The first element (position {@code 0}) in the {@code Stream} will be 842 * the provided {@code seed}. For {@code n > 0}, the element at position 843 * {@code n}, will be the result of applying the function {@code f} to the 844 * element at position {@code n - 1}. 845 * 846 * @param <T> the type of stream elements 847 * @param seed the initial element 848 * @param f a function to be applied to to the previous element to produce 849 * a new element 850 * @return a new sequential {@code Stream} 851 */ 852 public static<T> Stream<T> iterate(final T seed, final UnaryOperator<T> f) { 853 Objects.requireNonNull(f); 854 final Iterator<T> iterator = new Iterator<T>() { 855 @SuppressWarnings("unchecked") 856 T t = (T) Streams.NONE; 857 858 @Override 859 public boolean hasNext() { 860 return true; 861 } 862 863 @Override 864 public T next() { 865 return t = (t == Streams.NONE) ? seed : f.apply(t); 866 } 867 }; 868 return StreamSupport.stream(Spliterators.spliteratorUnknownSize( 869 iterator, 870 Spliterator.ORDERED | Spliterator.IMMUTABLE), false); 871 } 872 873 /** 874 * Returns a sequential {@code Stream} where each element is 875 * generated by a {@code Supplier}. This is suitable for generating 876 * constant streams, streams of random elements, etc. 877 * 878 * @param <T> the type of stream elements 879 * @param s the {@code Supplier} of generated elements 880 * @return a new sequential {@code Stream} 881 */ 882 public static<T> Stream<T> generate(Supplier<T> s) { 883 Objects.requireNonNull(s); 884 return StreamSupport.stream( 885 new StreamSpliterators.InfiniteSupplyingSpliterator.OfRef<>(Long.MAX_VALUE, s), false); 886 } 887 888 /** 889 * Creates a lazy concatenated {@code Stream} whose elements are all the 890 * elements of a first {@code Stream} succeeded by all the elements of the 891 * second {@code Stream}. The resulting stream is ordered if both 892 * of the input streams are ordered, and parallel if either of the input 893 * streams is parallel. 894 * 895 * @param <T> The type of stream elements 896 * @param a the first stream 897 * @param b the second stream to concatenate on to end of the first 898 * stream 899 * @return the concatenation of the two input streams 900 */ 901 public static <T> Stream<T> concat(Stream<? extends T> a, Stream<? extends T> b) { 902 Objects.requireNonNull(a); 903 Objects.requireNonNull(b); 904 905 @SuppressWarnings("unchecked") 906 Spliterator<T> split = new Streams.ConcatSpliterator.OfRef<>( 907 (Spliterator<T>) a.spliterator(), (Spliterator<T>) b.spliterator()); 908 return StreamSupport.stream(split, a.isParallel() || b.isParallel()); 909 } 910 911 /** 912 * A mutable builder for a {@code Stream}. This allows the creation of a 913 * {@code Stream} by generating elements individually and adding them to the 914 * {@code Builder} (without the copying overhead that comes from using 915 * an {@code ArrayList} as a temporary buffer.) 916 * 917 * <p>A {@code Stream.Builder} has a lifecycle, where it starts in a building 918 * phase, during which elements can be added, and then transitions to a built 919 * phase, after which elements may not be added. The built phase begins 920 * when the {@link #build()} method is called, which creates an ordered 921 * {@code Stream} whose elements are the elements that were added to the stream 922 * builder, in the order they were added. 923 * 924 * @param <T> the type of stream elements 925 * @see Stream#builder() 926 * @since 1.8 927 */ 928 public interface Builder<T> extends Consumer<T> { 929 930 /** 931 * Adds an element to the stream being built. 932 * 933 * @throws IllegalStateException if the builder has already transitioned to 934 * the built state 935 */ 936 @Override 937 void accept(T t); 938 939 /** 940 * Adds an element to the stream being built. 941 * 942 * @implSpec 943 * The default implementation behaves as if: 944 * <pre>{@code 945 * accept(t) 946 * return this; 947 * }</pre> 948 * 949 * @param t the element to add 950 * @return {@code this} builder 951 * @throws IllegalStateException if the builder has already transitioned to 952 * the built state 953 */ 954 default Builder<T> add(T t) { 955 accept(t); 956 return this; 957 } 958 959 /** 960 * Builds the stream, transitioning this builder to the built state. 961 * An {@code IllegalStateException} is thrown if there are further attempts 962 * to operate on the builder after it has entered the built state. 963 * 964 * @return the built stream 965 * @throws IllegalStateException if the builder has already transitioned to 966 * the built state 967 */ 968 Stream<T> build(); 969 970 } 971 }