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.util.Arrays; 29 import java.util.Collection; 30 import java.util.Comparator; 31 import java.util.Iterator; 32 import java.util.Objects; 33 import java.util.Optional; 34 import java.util.Spliterator; 35 import java.util.Spliterators; 36 import java.util.concurrent.ConcurrentHashMap; 37 import java.util.function.BiConsumer; 38 import java.util.function.BiFunction; 39 import java.util.function.BinaryOperator; 40 import java.util.function.Consumer; 41 import java.util.function.Function; 42 import java.util.function.IntFunction; 43 import java.util.function.Predicate; 44 import java.util.function.Supplier; 45 import java.util.function.ToDoubleFunction; 46 import java.util.function.ToIntFunction; 47 import java.util.function.ToLongFunction; 48 import java.util.function.UnaryOperator; 49 50 /** 51 * A sequence of elements supporting sequential and parallel aggregate 52 * operations. The following example illustrates an aggregate operation using 53 * {@link Stream} and {@link IntStream}: 54 * 55 * <pre>{@code 56 * int sum = widgets.stream() 57 * .filter(w -> w.getColor() == RED) 58 * .mapToInt(w -> w.getWeight()) 59 * .sum(); 60 * }</pre> 61 * 62 * In this example, {@code widgets} is a {@code Collection<Widget>}. We create 63 * a stream of {@code Widget} objects via {@link Collection#stream Collection.stream()}, 64 * filter it to produce a stream containing only the red widgets, and then 65 * transform it into a stream of {@code int} values representing the weight of 66 * each red widget. Then this stream is summed to produce a total weight. 67 * 68 * <p>In addition to {@code Stream}, which is a stream of object references, 69 * there are primitive specializations for {@link IntStream}, {@link LongStream}, 70 * and {@link DoubleStream}, all of which are referred to as "streams" and 71 * conform to the characteristics and restrictions described here. 72 * 73 * <p>To perform a computation, stream 74 * <a href="package-summary.html#StreamOps">operations</a> are composed into a 75 * <em>stream pipeline</em>. A stream pipeline consists of a source (which 76 * might be an array, a collection, a generator function, an I/O channel, 77 * etc), zero or more <em>intermediate operations</em> (which transform a 78 * stream into another stream, such as {@link Stream#filter(Predicate)}), and a 79 * <em>terminal operation</em> (which produces a result or side-effect, such 80 * as {@link Stream#count()} or {@link Stream#forEach(Consumer)}). 81 * Streams are lazy; computation on the source data is only performed when the 82 * terminal operation is initiated, and source elements are consumed only 83 * as needed. 84 * 85 * <p>Collections and streams, while bearing some superficial similarities, 86 * have different goals. Collections are primarily concerned with the efficient 87 * management of, and access to, their elements. By contrast, streams do not 88 * provide a means to directly access or manipulate their elements, and are 89 * instead concerned with declaratively describing their source and the 90 * computational operations which will be performed in aggregate on that source. 91 * However, if the provided stream operations do not offer the desired 92 * functionality, the {@link #iterator()} and {@link #spliterator()} operations 93 * can be used to perform a controlled traversal. 94 * 95 * <p>A stream pipeline, like the "widgets" example above, can be viewed as 96 * a <em>query</em> on the stream source. Unless the source was explicitly 97 * designed for concurrent modification (such as a {@link ConcurrentHashMap}), 98 * unpredictable or erroneous behavior may result from modifying the stream 99 * source while it is being queried. 100 * 101 * <p>Most stream operations accept parameters that describe user-specified 102 * behavior, such as the lambda expression {@code w -> w.getWeight()} passed to 103 * {@code mapToInt} in the example above. To preserve correct behavior, 104 * these <em>behavioral parameters</em>: 105 * <ul> 106 * <li>must be <a href="package-summary.html#NonInterference">non-interfering</a> 107 * (they do not modify the stream source); and</li> 108 * <li>in most cases must be <a href="package-summary.html#Statelessness">stateless</a> 109 * (their result should not depend on any state that might change during execution 110 * of the stream pipeline).</li> 111 * </ul> 112 * 113 * <p>Such parameters are always instances of a 114 * <a href="../function/package-summary.html">functional interface</a> such 115 * as {@link java.util.function.Function}, and are often lambda expressions or 116 * method references. Unless otherwise specified these parameters must be 117 * <em>non-null</em>. 118 * 119 * <p>A stream should be operated on (invoking an intermediate or terminal stream 120 * operation) only once. This rules out, for example, "forked" streams, where 121 * the same source feeds two or more pipelines, or multiple traversals of the 122 * same stream. A stream implementation may throw {@link IllegalStateException} 123 * if it detects that the stream is being reused. However, since some stream 124 * operations may return their receiver rather than a new stream object, it may 125 * not be possible to detect reuse in all cases. 126 * 127 * <p>Streams have a {@link #close()} method and implement {@link AutoCloseable}, 128 * but nearly all stream instances do not actually need to be closed after use. 129 * Generally, only streams whose source is an IO channel will require closing. Most streams 130 * are backed by collections, arrays, or generating functions, which require no 131 * special resource management. (If a stream does require closing, it can be 132 * declared as a resource in a {@code try}-with-resources statement.) 133 * 134 * <p>Stream pipelines may execute either sequentially or in 135 * <a href="package-summary.html#Parallelism">parallel</a>. This 136 * execution mode is a property of the stream. Streams are created 137 * with an initial choice of sequential or parallel execution. (For example, 138 * {@link Collection#stream() Collection.stream()} creates a sequential stream, 139 * and {@link Collection#parallelStream() Collection.parallelStream()} creates 140 * a parallel one.) This choice of execution mode may be modified by the 141 * {@link #sequential()} or {@link #parallel()} methods, and may be queried with 142 * the {@link #isParallel()} method. 143 * 144 * @param <T> the type of the stream elements 145 * @since 1.8 146 * @see IntStream 147 * @see LongStream 148 * @see DoubleStream 149 * @see <a href="package-summary.html">java.util.stream</a> 150 */ 151 public interface Stream<T> extends BaseStream<T, Stream<T>> { 152 153 /** 154 * Returns a stream consisting of the elements of this stream that match 155 * the given predicate. 156 * 157 * <p>This is an <a href="package-summary.html#StreamOps">intermediate 158 * operation</a>. 159 * 160 * @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>, 161 * <a href="package-summary.html#Statelessness">stateless</a> 162 * predicate to apply to each element to determine if it 163 * should be included 164 * @return the new stream 165 */ filter(Predicate<? super T> predicate)166 Stream<T> filter(Predicate<? super T> predicate); 167 168 /** 169 * Returns a stream consisting of the results of applying the given 170 * function to the elements of this stream. 171 * 172 * <p>This is an <a href="package-summary.html#StreamOps">intermediate 173 * operation</a>. 174 * 175 * @param <R> The element type of the new stream 176 * @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>, 177 * <a href="package-summary.html#Statelessness">stateless</a> 178 * function to apply to each element 179 * @return the new stream 180 */ map(Function<? super T, ? extends R> mapper)181 <R> Stream<R> map(Function<? super T, ? extends R> mapper); 182 183 /** 184 * Returns an {@code IntStream} consisting of the results of applying the 185 * given function to the elements of this stream. 186 * 187 * <p>This is an <a href="package-summary.html#StreamOps"> 188 * intermediate operation</a>. 189 * 190 * @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>, 191 * <a href="package-summary.html#Statelessness">stateless</a> 192 * function to apply to each element 193 * @return the new stream 194 */ mapToInt(ToIntFunction<? super T> mapper)195 IntStream mapToInt(ToIntFunction<? super T> mapper); 196 197 /** 198 * Returns a {@code LongStream} consisting of the results of applying the 199 * given function to the elements of this stream. 200 * 201 * <p>This is an <a href="package-summary.html#StreamOps">intermediate 202 * operation</a>. 203 * 204 * @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>, 205 * <a href="package-summary.html#Statelessness">stateless</a> 206 * function to apply to each element 207 * @return the new stream 208 */ mapToLong(ToLongFunction<? super T> mapper)209 LongStream mapToLong(ToLongFunction<? super T> mapper); 210 211 /** 212 * Returns a {@code DoubleStream} consisting of the results of applying the 213 * given function to the elements of this stream. 214 * 215 * <p>This is an <a href="package-summary.html#StreamOps">intermediate 216 * operation</a>. 217 * 218 * @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>, 219 * <a href="package-summary.html#Statelessness">stateless</a> 220 * function to apply to each element 221 * @return the new stream 222 */ mapToDouble(ToDoubleFunction<? super T> mapper)223 DoubleStream mapToDouble(ToDoubleFunction<? super T> mapper); 224 225 /** 226 * Returns a stream consisting of the results of replacing each element of 227 * this stream with the contents of a mapped stream produced by applying 228 * the provided mapping function to each element. Each mapped stream is 229 * {@link java.util.stream.BaseStream#close() closed} after its contents 230 * have been placed into this stream. (If a mapped stream is {@code null} 231 * an empty stream is used, instead.) 232 * 233 * <p>This is an <a href="package-summary.html#StreamOps">intermediate 234 * operation</a>. 235 * 236 * @apiNote 237 * The {@code flatMap()} operation has the effect of applying a one-to-many 238 * transformation to the elements of the stream, and then flattening the 239 * resulting elements into a new stream. 240 * 241 * <p><b>Examples.</b> 242 * 243 * <p>If {@code orders} is a stream of purchase orders, and each purchase 244 * order contains a collection of line items, then the following produces a 245 * stream containing all the line items in all the orders: 246 * <pre>{@code 247 * orders.flatMap(order -> order.getLineItems().stream())... 248 * }</pre> 249 * 250 * <p>If {@code path} is the path to a file, then the following produces a 251 * stream of the {@code words} contained in that file: 252 * <pre>{@code 253 * Stream<String> lines = Files.lines(path, StandardCharsets.UTF_8); 254 * Stream<String> words = lines.flatMap(line -> Stream.of(line.split(" +"))); 255 * }</pre> 256 * The {@code mapper} function passed to {@code flatMap} splits a line, 257 * using a simple regular expression, into an array of words, and then 258 * creates a stream of words from that array. 259 * 260 * @param <R> The element type of the new stream 261 * @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>, 262 * <a href="package-summary.html#Statelessness">stateless</a> 263 * function to apply to each element which produces a stream 264 * of new values 265 * @return the new stream 266 */ flatMap(Function<? super T, ? extends Stream<? extends R>> mapper)267 <R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper); 268 269 /** 270 * Returns an {@code IntStream} consisting of the results of replacing each 271 * element of this stream with the contents of a mapped stream produced by 272 * applying the provided mapping function to each element. Each mapped 273 * stream is {@link java.util.stream.BaseStream#close() closed} after its 274 * contents have been placed into this stream. (If a mapped stream is 275 * {@code null} an empty stream is used, instead.) 276 * 277 * <p>This is an <a href="package-summary.html#StreamOps">intermediate 278 * operation</a>. 279 * 280 * @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>, 281 * <a href="package-summary.html#Statelessness">stateless</a> 282 * function to apply to each element which produces a stream 283 * of new values 284 * @return the new stream 285 * @see #flatMap(Function) 286 */ flatMapToInt(Function<? super T, ? extends IntStream> mapper)287 IntStream flatMapToInt(Function<? super T, ? extends IntStream> mapper); 288 289 /** 290 * Returns an {@code LongStream} consisting of the results of replacing each 291 * element of this stream with the contents of a mapped stream produced by 292 * applying the provided mapping function to each element. Each mapped 293 * stream is {@link java.util.stream.BaseStream#close() closed} after its 294 * contents have been placed into this stream. (If a mapped stream is 295 * {@code null} an empty stream is used, instead.) 296 * 297 * <p>This is an <a href="package-summary.html#StreamOps">intermediate 298 * operation</a>. 299 * 300 * @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>, 301 * <a href="package-summary.html#Statelessness">stateless</a> 302 * function to apply to each element which produces a stream 303 * of new values 304 * @return the new stream 305 * @see #flatMap(Function) 306 */ flatMapToLong(Function<? super T, ? extends LongStream> mapper)307 LongStream flatMapToLong(Function<? super T, ? extends LongStream> mapper); 308 309 /** 310 * Returns an {@code DoubleStream} consisting of the results of replacing 311 * each element of this stream with the contents of a mapped stream produced 312 * by applying the provided mapping function to each element. Each mapped 313 * stream is {@link java.util.stream.BaseStream#close() closed} after its 314 * contents have placed been into this stream. (If a mapped stream is 315 * {@code null} an empty stream is used, instead.) 316 * 317 * <p>This is an <a href="package-summary.html#StreamOps">intermediate 318 * operation</a>. 319 * 320 * @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>, 321 * <a href="package-summary.html#Statelessness">stateless</a> 322 * function to apply to each element which produces a stream 323 * of new values 324 * @return the new stream 325 * @see #flatMap(Function) 326 */ flatMapToDouble(Function<? super T, ? extends DoubleStream> mapper)327 DoubleStream flatMapToDouble(Function<? super T, ? extends DoubleStream> mapper); 328 329 /** 330 * Returns a stream consisting of the distinct elements (according to 331 * {@link Object#equals(Object)}) of this stream. 332 * 333 * <p>For ordered streams, the selection of distinct elements is stable 334 * (for duplicated elements, the element appearing first in the encounter 335 * order is preserved.) For unordered streams, no stability guarantees 336 * are made. 337 * 338 * <p>This is a <a href="package-summary.html#StreamOps">stateful 339 * intermediate operation</a>. 340 * 341 * @apiNote 342 * Preserving stability for {@code distinct()} in parallel pipelines is 343 * relatively expensive (requires that the operation act as a full barrier, 344 * with substantial buffering overhead), and stability is often not needed. 345 * Using an unordered stream source (such as {@link #generate(Supplier)}) 346 * or removing the ordering constraint with {@link #unordered()} may result 347 * in significantly more efficient execution for {@code distinct()} in parallel 348 * pipelines, if the semantics of your situation permit. If consistency 349 * with encounter order is required, and you are experiencing poor performance 350 * or memory utilization with {@code distinct()} in parallel pipelines, 351 * switching to sequential execution with {@link #sequential()} may improve 352 * performance. 353 * 354 * @return the new stream 355 */ distinct()356 Stream<T> distinct(); 357 358 /** 359 * Returns a stream consisting of the elements of this stream, sorted 360 * according to natural order. If the elements of this stream are not 361 * {@code Comparable}, a {@code java.lang.ClassCastException} may be thrown 362 * when the terminal operation is executed. 363 * 364 * <p>For ordered streams, the sort is stable. For unordered streams, no 365 * stability guarantees are made. 366 * 367 * <p>This is a <a href="package-summary.html#StreamOps">stateful 368 * intermediate operation</a>. 369 * 370 * @return the new stream 371 */ sorted()372 Stream<T> sorted(); 373 374 /** 375 * Returns a stream consisting of the elements of this stream, sorted 376 * according to the provided {@code Comparator}. 377 * 378 * <p>For ordered streams, the sort is stable. For unordered streams, no 379 * stability guarantees are made. 380 * 381 * <p>This is a <a href="package-summary.html#StreamOps">stateful 382 * intermediate operation</a>. 383 * 384 * @param comparator a <a href="package-summary.html#NonInterference">non-interfering</a>, 385 * <a href="package-summary.html#Statelessness">stateless</a> 386 * {@code Comparator} to be used to compare stream elements 387 * @return the new stream 388 */ sorted(Comparator<? super T> comparator)389 Stream<T> sorted(Comparator<? super T> comparator); 390 391 /** 392 * Returns a stream consisting of the elements of this stream, additionally 393 * performing the provided action on each element as elements are consumed 394 * from the resulting stream. 395 * 396 * <p>This is an <a href="package-summary.html#StreamOps">intermediate 397 * operation</a>. 398 * 399 * <p>For parallel stream pipelines, the action may be called at 400 * whatever time and in whatever thread the element is made available by the 401 * upstream operation. If the action modifies shared state, 402 * it is responsible for providing the required synchronization. 403 * 404 * @apiNote This method exists mainly to support debugging, where you want 405 * to see the elements as they flow past a certain point in a pipeline: 406 * <pre>{@code 407 * Stream.of("one", "two", "three", "four") 408 * .filter(e -> e.length() > 3) 409 * .peek(e -> System.out.println("Filtered value: " + e)) 410 * .map(String::toUpperCase) 411 * .peek(e -> System.out.println("Mapped value: " + e)) 412 * .collect(Collectors.toList()); 413 * }</pre> 414 * 415 * @param action a <a href="package-summary.html#NonInterference"> 416 * non-interfering</a> action to perform on the elements as 417 * they are consumed from the stream 418 * @return the new stream 419 */ peek(Consumer<? super T> action)420 Stream<T> peek(Consumer<? super T> action); 421 422 /** 423 * Returns a stream consisting of the elements of this stream, truncated 424 * to be no longer than {@code maxSize} in length. 425 * 426 * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting 427 * stateful intermediate operation</a>. 428 * 429 * @apiNote 430 * While {@code limit()} is generally a cheap operation on sequential 431 * stream pipelines, it can be quite expensive on ordered parallel pipelines, 432 * especially for large values of {@code maxSize}, since {@code limit(n)} 433 * is constrained to return not just any <em>n</em> elements, but the 434 * <em>first n</em> elements in the encounter order. Using an unordered 435 * stream source (such as {@link #generate(Supplier)}) or removing the 436 * ordering constraint with {@link #unordered()} may result in significant 437 * speedups of {@code limit()} in parallel pipelines, if the semantics of 438 * your situation permit. If consistency with encounter order is required, 439 * and you are experiencing poor performance or memory utilization with 440 * {@code limit()} in parallel pipelines, switching to sequential execution 441 * with {@link #sequential()} may improve performance. 442 * 443 * @param maxSize the number of elements the stream should be limited to 444 * @return the new stream 445 * @throws IllegalArgumentException if {@code maxSize} is negative 446 */ limit(long maxSize)447 Stream<T> limit(long maxSize); 448 449 /** 450 * Returns a stream consisting of the remaining elements of this stream 451 * after discarding the first {@code n} elements of the stream. 452 * If this stream contains fewer than {@code n} elements then an 453 * empty stream will be returned. 454 * 455 * <p>This is a <a href="package-summary.html#StreamOps">stateful 456 * intermediate operation</a>. 457 * 458 * @apiNote 459 * While {@code skip()} is generally a cheap operation on sequential 460 * stream pipelines, it can be quite expensive on ordered parallel pipelines, 461 * especially for large values of {@code n}, since {@code skip(n)} 462 * is constrained to skip not just any <em>n</em> elements, but the 463 * <em>first n</em> elements in the encounter order. Using an unordered 464 * stream source (such as {@link #generate(Supplier)}) or removing the 465 * ordering constraint with {@link #unordered()} may result in significant 466 * speedups of {@code skip()} in parallel pipelines, if the semantics of 467 * your situation permit. If consistency with encounter order is required, 468 * and you are experiencing poor performance or memory utilization with 469 * {@code skip()} in parallel pipelines, switching to sequential execution 470 * with {@link #sequential()} may improve performance. 471 * 472 * @param n the number of leading elements to skip 473 * @return the new stream 474 * @throws IllegalArgumentException if {@code n} is negative 475 */ skip(long n)476 Stream<T> skip(long n); 477 478 /** 479 * Performs an action for each element of this stream. 480 * 481 * <p>This is a <a href="package-summary.html#StreamOps">terminal 482 * operation</a>. 483 * 484 * <p>The behavior of this operation is explicitly nondeterministic. 485 * For parallel stream pipelines, this operation does <em>not</em> 486 * guarantee to respect the encounter order of the stream, as doing so 487 * would sacrifice the benefit of parallelism. For any given element, the 488 * action may be performed at whatever time and in whatever thread the 489 * library chooses. If the action accesses shared state, it is 490 * responsible for providing the required synchronization. 491 * 492 * @param action a <a href="package-summary.html#NonInterference"> 493 * non-interfering</a> action to perform on the elements 494 */ forEach(Consumer<? super T> action)495 void forEach(Consumer<? super T> action); 496 497 /** 498 * Performs an action for each element of this stream, in the encounter 499 * order of the stream if the stream has a defined encounter order. 500 * 501 * <p>This is a <a href="package-summary.html#StreamOps">terminal 502 * operation</a>. 503 * 504 * <p>This operation processes the elements one at a time, in encounter 505 * order if one exists. Performing the action for one element 506 * <a href="../concurrent/package-summary.html#MemoryVisibility"><i>happens-before</i></a> 507 * performing the action for subsequent elements, but for any given element, 508 * the action may be performed in whatever thread the library chooses. 509 * 510 * @param action a <a href="package-summary.html#NonInterference"> 511 * non-interfering</a> action to perform on the elements 512 * @see #forEach(Consumer) 513 */ forEachOrdered(Consumer<? super T> action)514 void forEachOrdered(Consumer<? super T> action); 515 516 /** 517 * Returns an array containing the elements of this stream. 518 * 519 * <p>This is a <a href="package-summary.html#StreamOps">terminal 520 * operation</a>. 521 * 522 * @return an array containing the elements of this stream 523 */ toArray()524 Object[] toArray(); 525 526 /** 527 * Returns an array containing the elements of this stream, using the 528 * provided {@code generator} function to allocate the returned array, as 529 * well as any additional arrays that might be required for a partitioned 530 * execution or for resizing. 531 * 532 * <p>This is a <a href="package-summary.html#StreamOps">terminal 533 * operation</a>. 534 * 535 * @apiNote 536 * The generator function takes an integer, which is the size of the 537 * desired array, and produces an array of the desired size. This can be 538 * concisely expressed with an array constructor reference: 539 * <pre>{@code 540 * Person[] men = people.stream() 541 * .filter(p -> p.getGender() == MALE) 542 * .toArray(Person[]::new); 543 * }</pre> 544 * 545 * @param <A> the element type of the resulting array 546 * @param generator a function which produces a new array of the desired 547 * type and the provided length 548 * @return an array containing the elements in this stream 549 * @throws ArrayStoreException if the runtime type of the array returned 550 * from the array generator is not a supertype of the runtime type of every 551 * element in this stream 552 */ toArray(IntFunction<A[]> generator)553 <A> A[] toArray(IntFunction<A[]> generator); 554 555 /** 556 * Performs a <a href="package-summary.html#Reduction">reduction</a> on the 557 * elements of this stream, using the provided identity value and an 558 * <a href="package-summary.html#Associativity">associative</a> 559 * accumulation function, and returns the reduced value. This is equivalent 560 * to: 561 * <pre>{@code 562 * T result = identity; 563 * for (T element : this stream) 564 * result = accumulator.apply(result, element) 565 * return result; 566 * }</pre> 567 * 568 * but is not constrained to execute sequentially. 569 * 570 * <p>The {@code identity} value must be an identity for the accumulator 571 * function. This means that for all {@code t}, 572 * {@code accumulator.apply(identity, t)} is equal to {@code t}. 573 * The {@code accumulator} function must be an 574 * <a href="package-summary.html#Associativity">associative</a> function. 575 * 576 * <p>This is a <a href="package-summary.html#StreamOps">terminal 577 * operation</a>. 578 * 579 * @apiNote Sum, min, max, average, and string concatenation are all special 580 * cases of reduction. Summing a stream of numbers can be expressed as: 581 * 582 * <pre>{@code 583 * Integer sum = integers.reduce(0, (a, b) -> a+b); 584 * }</pre> 585 * 586 * or: 587 * 588 * <pre>{@code 589 * Integer sum = integers.reduce(0, Integer::sum); 590 * }</pre> 591 * 592 * <p>While this may seem a more roundabout way to perform an aggregation 593 * compared to simply mutating a running total in a loop, reduction 594 * operations parallelize more gracefully, without needing additional 595 * synchronization and with greatly reduced risk of data races. 596 * 597 * @param identity the identity value for the accumulating function 598 * @param accumulator an <a href="package-summary.html#Associativity">associative</a>, 599 * <a href="package-summary.html#NonInterference">non-interfering</a>, 600 * <a href="package-summary.html#Statelessness">stateless</a> 601 * function for combining two values 602 * @return the result of the reduction 603 */ reduce(T identity, BinaryOperator<T> accumulator)604 T reduce(T identity, BinaryOperator<T> accumulator); 605 606 /** 607 * Performs a <a href="package-summary.html#Reduction">reduction</a> on the 608 * elements of this stream, using an 609 * <a href="package-summary.html#Associativity">associative</a> accumulation 610 * function, and returns an {@code Optional} describing the reduced value, 611 * if any. This is equivalent to: 612 * <pre>{@code 613 * boolean foundAny = false; 614 * T result = null; 615 * for (T element : this stream) { 616 * if (!foundAny) { 617 * foundAny = true; 618 * result = element; 619 * } 620 * else 621 * result = accumulator.apply(result, element); 622 * } 623 * return foundAny ? Optional.of(result) : Optional.empty(); 624 * }</pre> 625 * 626 * but is not constrained to execute sequentially. 627 * 628 * <p>The {@code accumulator} function must be an 629 * <a href="package-summary.html#Associativity">associative</a> function. 630 * 631 * <p>This is a <a href="package-summary.html#StreamOps">terminal 632 * operation</a>. 633 * 634 * @param accumulator an <a href="package-summary.html#Associativity">associative</a>, 635 * <a href="package-summary.html#NonInterference">non-interfering</a>, 636 * <a href="package-summary.html#Statelessness">stateless</a> 637 * function for combining two values 638 * @return an {@link Optional} describing the result of the reduction 639 * @throws NullPointerException if the result of the reduction is null 640 * @see #reduce(Object, BinaryOperator) 641 * @see #min(Comparator) 642 * @see #max(Comparator) 643 */ reduce(BinaryOperator<T> accumulator)644 Optional<T> reduce(BinaryOperator<T> accumulator); 645 646 /** 647 * Performs a <a href="package-summary.html#Reduction">reduction</a> on the 648 * elements of this stream, using the provided identity, accumulation and 649 * combining functions. This is equivalent to: 650 * <pre>{@code 651 * U result = identity; 652 * for (T element : this stream) 653 * result = accumulator.apply(result, element) 654 * return result; 655 * }</pre> 656 * 657 * but is not constrained to execute sequentially. 658 * 659 * <p>The {@code identity} value must be an identity for the combiner 660 * function. This means that for all {@code u}, {@code combiner(identity, u)} 661 * is equal to {@code u}. Additionally, the {@code combiner} function 662 * must be compatible with the {@code accumulator} function; for all 663 * {@code u} and {@code t}, the following must hold: 664 * <pre>{@code 665 * combiner.apply(u, accumulator.apply(identity, t)) == accumulator.apply(u, t) 666 * }</pre> 667 * 668 * <p>This is a <a href="package-summary.html#StreamOps">terminal 669 * operation</a>. 670 * 671 * @apiNote Many reductions using this form can be represented more simply 672 * by an explicit combination of {@code map} and {@code reduce} operations. 673 * The {@code accumulator} function acts as a fused mapper and accumulator, 674 * which can sometimes be more efficient than separate mapping and reduction, 675 * such as when knowing the previously reduced value allows you to avoid 676 * some computation. 677 * 678 * @param <U> The type of the result 679 * @param identity the identity value for the combiner function 680 * @param accumulator an <a href="package-summary.html#Associativity">associative</a>, 681 * <a href="package-summary.html#NonInterference">non-interfering</a>, 682 * <a href="package-summary.html#Statelessness">stateless</a> 683 * function for incorporating an additional element into a result 684 * @param combiner an <a href="package-summary.html#Associativity">associative</a>, 685 * <a href="package-summary.html#NonInterference">non-interfering</a>, 686 * <a href="package-summary.html#Statelessness">stateless</a> 687 * function for combining two values, which must be 688 * compatible with the accumulator function 689 * @return the result of the reduction 690 * @see #reduce(BinaryOperator) 691 * @see #reduce(Object, BinaryOperator) 692 */ reduce(U identity, BiFunction<U, ? super T, U> accumulator, BinaryOperator<U> combiner)693 <U> U reduce(U identity, 694 BiFunction<U, ? super T, U> accumulator, 695 BinaryOperator<U> combiner); 696 697 /** 698 * Performs a <a href="package-summary.html#MutableReduction">mutable 699 * reduction</a> operation on the elements of this stream. A mutable 700 * reduction is one in which the reduced value is a mutable result container, 701 * such as an {@code ArrayList}, and elements are incorporated by updating 702 * the state of the result rather than by replacing the result. This 703 * produces a result equivalent to: 704 * <pre>{@code 705 * R result = supplier.get(); 706 * for (T element : this stream) 707 * accumulator.accept(result, element); 708 * return result; 709 * }</pre> 710 * 711 * <p>Like {@link #reduce(Object, BinaryOperator)}, {@code collect} operations 712 * can be parallelized without requiring additional synchronization. 713 * 714 * <p>This is a <a href="package-summary.html#StreamOps">terminal 715 * operation</a>. 716 * 717 * @apiNote There are many existing classes in the JDK whose signatures are 718 * well-suited for use with method references as arguments to {@code collect()}. 719 * For example, the following will accumulate strings into an {@code ArrayList}: 720 * <pre>{@code 721 * List<String> asList = stringStream.collect(ArrayList::new, ArrayList::add, 722 * ArrayList::addAll); 723 * }</pre> 724 * 725 * <p>The following will take a stream of strings and concatenates them into a 726 * single string: 727 * <pre>{@code 728 * String concat = stringStream.collect(StringBuilder::new, StringBuilder::append, 729 * StringBuilder::append) 730 * .toString(); 731 * }</pre> 732 * 733 * @param <R> type of the result 734 * @param supplier a function that creates a new result container. For a 735 * parallel execution, this function may be called 736 * multiple times and must return a fresh value each time. 737 * @param accumulator an <a href="package-summary.html#Associativity">associative</a>, 738 * <a href="package-summary.html#NonInterference">non-interfering</a>, 739 * <a href="package-summary.html#Statelessness">stateless</a> 740 * function for incorporating an additional element into a result 741 * @param combiner an <a href="package-summary.html#Associativity">associative</a>, 742 * <a href="package-summary.html#NonInterference">non-interfering</a>, 743 * <a href="package-summary.html#Statelessness">stateless</a> 744 * function for combining two values, which must be 745 * compatible with the accumulator function 746 * @return the result of the reduction 747 */ collect(Supplier<R> supplier, BiConsumer<R, ? super T> accumulator, BiConsumer<R, R> combiner)748 <R> R collect(Supplier<R> supplier, 749 BiConsumer<R, ? super T> accumulator, 750 BiConsumer<R, R> combiner); 751 752 /** 753 * Performs a <a href="package-summary.html#MutableReduction">mutable 754 * reduction</a> operation on the elements of this stream using a 755 * {@code Collector}. A {@code Collector} 756 * encapsulates the functions used as arguments to 757 * {@link #collect(Supplier, BiConsumer, BiConsumer)}, allowing for reuse of 758 * collection strategies and composition of collect operations such as 759 * multiple-level grouping or partitioning. 760 * 761 * <p>If the stream is parallel, and the {@code Collector} 762 * is {@link Collector.Characteristics#CONCURRENT concurrent}, and 763 * either the stream is unordered or the collector is 764 * {@link Collector.Characteristics#UNORDERED unordered}, 765 * then a concurrent reduction will be performed (see {@link Collector} for 766 * details on concurrent reduction.) 767 * 768 * <p>This is a <a href="package-summary.html#StreamOps">terminal 769 * operation</a>. 770 * 771 * <p>When executed in parallel, multiple intermediate results may be 772 * instantiated, populated, and merged so as to maintain isolation of 773 * mutable data structures. Therefore, even when executed in parallel 774 * with non-thread-safe data structures (such as {@code ArrayList}), no 775 * additional synchronization is needed for a parallel reduction. 776 * 777 * @apiNote 778 * The following will accumulate strings into an ArrayList: 779 * <pre>{@code 780 * List<String> asList = stringStream.collect(Collectors.toList()); 781 * }</pre> 782 * 783 * <p>The following will classify {@code Person} objects by city: 784 * <pre>{@code 785 * Map<String, List<Person>> peopleByCity 786 * = personStream.collect(Collectors.groupingBy(Person::getCity)); 787 * }</pre> 788 * 789 * <p>The following will classify {@code Person} objects by state and city, 790 * cascading two {@code Collector}s together: 791 * <pre>{@code 792 * Map<String, Map<String, List<Person>>> peopleByStateAndCity 793 * = personStream.collect(Collectors.groupingBy(Person::getState, 794 * Collectors.groupingBy(Person::getCity))); 795 * }</pre> 796 * 797 * @param <R> the type of the result 798 * @param <A> the intermediate accumulation type of the {@code Collector} 799 * @param collector the {@code Collector} describing the reduction 800 * @return the result of the reduction 801 * @see #collect(Supplier, BiConsumer, BiConsumer) 802 * @see Collectors 803 */ collect(Collector<? super T, A, R> collector)804 <R, A> R collect(Collector<? super T, A, R> collector); 805 806 /** 807 * Returns the minimum element of this stream according to the provided 808 * {@code Comparator}. This is a special case of a 809 * <a href="package-summary.html#Reduction">reduction</a>. 810 * 811 * <p>This is a <a href="package-summary.html#StreamOps">terminal operation</a>. 812 * 813 * @param comparator a <a href="package-summary.html#NonInterference">non-interfering</a>, 814 * <a href="package-summary.html#Statelessness">stateless</a> 815 * {@code Comparator} to compare elements of this stream 816 * @return an {@code Optional} describing the minimum element of this stream, 817 * or an empty {@code Optional} if the stream is empty 818 * @throws NullPointerException if the minimum element is null 819 */ min(Comparator<? super T> comparator)820 Optional<T> min(Comparator<? super T> comparator); 821 822 /** 823 * Returns the maximum element of this stream according to the provided 824 * {@code Comparator}. This is a special case of a 825 * <a href="package-summary.html#Reduction">reduction</a>. 826 * 827 * <p>This is a <a href="package-summary.html#StreamOps">terminal 828 * operation</a>. 829 * 830 * @param comparator a <a href="package-summary.html#NonInterference">non-interfering</a>, 831 * <a href="package-summary.html#Statelessness">stateless</a> 832 * {@code Comparator} to compare elements of this stream 833 * @return an {@code Optional} describing the maximum element of this stream, 834 * or an empty {@code Optional} if the stream is empty 835 * @throws NullPointerException if the maximum element is null 836 */ max(Comparator<? super T> comparator)837 Optional<T> max(Comparator<? super T> comparator); 838 839 /** 840 * Returns the count of elements in this stream. This is a special case of 841 * a <a href="package-summary.html#Reduction">reduction</a> and is 842 * equivalent to: 843 * <pre>{@code 844 * return mapToLong(e -> 1L).sum(); 845 * }</pre> 846 * 847 * <p>This is a <a href="package-summary.html#StreamOps">terminal operation</a>. 848 * 849 * @return the count of elements in this stream 850 */ count()851 long count(); 852 853 /** 854 * Returns whether any elements of this stream match the provided 855 * predicate. May not evaluate the predicate on all elements if not 856 * necessary for determining the result. If the stream is empty then 857 * {@code false} is returned and the predicate is not evaluated. 858 * 859 * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting 860 * terminal operation</a>. 861 * 862 * @apiNote 863 * This method evaluates the <em>existential quantification</em> of the 864 * predicate over the elements of the stream (for some x P(x)). 865 * 866 * @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>, 867 * <a href="package-summary.html#Statelessness">stateless</a> 868 * predicate to apply to elements of this stream 869 * @return {@code true} if any elements of the stream match the provided 870 * predicate, otherwise {@code false} 871 */ anyMatch(Predicate<? super T> predicate)872 boolean anyMatch(Predicate<? super T> predicate); 873 874 /** 875 * Returns whether all elements of this stream match the provided predicate. 876 * May not evaluate the predicate on all elements if not necessary for 877 * determining the result. If the stream is empty then {@code true} is 878 * returned and the predicate is not evaluated. 879 * 880 * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting 881 * terminal operation</a>. 882 * 883 * @apiNote 884 * This method evaluates the <em>universal quantification</em> of the 885 * predicate over the elements of the stream (for all x P(x)). If the 886 * stream is empty, the quantification is said to be <em>vacuously 887 * satisfied</em> and is always {@code true} (regardless of P(x)). 888 * 889 * @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>, 890 * <a href="package-summary.html#Statelessness">stateless</a> 891 * predicate to apply to elements of this stream 892 * @return {@code true} if either all elements of the stream match the 893 * provided predicate or the stream is empty, otherwise {@code false} 894 */ allMatch(Predicate<? super T> predicate)895 boolean allMatch(Predicate<? super T> predicate); 896 897 /** 898 * Returns whether no elements of this stream match the provided predicate. 899 * May not evaluate the predicate on all elements if not necessary for 900 * determining the result. If the stream is empty then {@code true} is 901 * returned and the predicate is not evaluated. 902 * 903 * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting 904 * terminal operation</a>. 905 * 906 * @apiNote 907 * This method evaluates the <em>universal quantification</em> of the 908 * negated predicate over the elements of the stream (for all x ~P(x)). If 909 * the stream is empty, the quantification is said to be vacuously satisfied 910 * and is always {@code true}, regardless of P(x). 911 * 912 * @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>, 913 * <a href="package-summary.html#Statelessness">stateless</a> 914 * predicate to apply to elements of this stream 915 * @return {@code true} if either no elements of the stream match the 916 * provided predicate or the stream is empty, otherwise {@code false} 917 */ noneMatch(Predicate<? super T> predicate)918 boolean noneMatch(Predicate<? super T> predicate); 919 920 /** 921 * Returns an {@link Optional} describing the first element of this stream, 922 * or an empty {@code Optional} if the stream is empty. If the stream has 923 * no encounter order, then any element may be returned. 924 * 925 * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting 926 * terminal operation</a>. 927 * 928 * @return an {@code Optional} describing the first element of this stream, 929 * or an empty {@code Optional} if the stream is empty 930 * @throws NullPointerException if the element selected is null 931 */ findFirst()932 Optional<T> findFirst(); 933 934 /** 935 * Returns an {@link Optional} describing some element of the stream, or an 936 * empty {@code Optional} if the stream is empty. 937 * 938 * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting 939 * terminal operation</a>. 940 * 941 * <p>The behavior of this operation is explicitly nondeterministic; it is 942 * free to select any element in the stream. This is to allow for maximal 943 * performance in parallel operations; the cost is that multiple invocations 944 * on the same source may not return the same result. (If a stable result 945 * is desired, use {@link #findFirst()} instead.) 946 * 947 * @return an {@code Optional} describing some element of this stream, or an 948 * empty {@code Optional} if the stream is empty 949 * @throws NullPointerException if the element selected is null 950 * @see #findFirst() 951 */ findAny()952 Optional<T> findAny(); 953 954 // Static factories 955 956 /** 957 * Returns a builder for a {@code Stream}. 958 * 959 * @param <T> type of elements 960 * @return a stream builder 961 */ builder()962 public static<T> Builder<T> builder() { 963 return new Streams.StreamBuilderImpl<>(); 964 } 965 966 /** 967 * Returns an empty sequential {@code Stream}. 968 * 969 * @param <T> the type of stream elements 970 * @return an empty sequential stream 971 */ empty()972 public static<T> Stream<T> empty() { 973 return StreamSupport.stream(Spliterators.<T>emptySpliterator(), false); 974 } 975 976 /** 977 * Returns a sequential {@code Stream} containing a single element. 978 * 979 * @param t the single element 980 * @param <T> the type of stream elements 981 * @return a singleton sequential stream 982 */ of(T t)983 public static<T> Stream<T> of(T t) { 984 return StreamSupport.stream(new Streams.StreamBuilderImpl<>(t), false); 985 } 986 987 /** 988 * Returns a sequential ordered stream whose elements are the specified values. 989 * 990 * @param <T> the type of stream elements 991 * @param values the elements of the new stream 992 * @return the new stream 993 */ 994 @SafeVarargs 995 @SuppressWarnings("varargs") // Creating a stream from an array is safe of(T... values)996 public static<T> Stream<T> of(T... values) { 997 return Arrays.stream(values); 998 } 999 1000 /** 1001 * Returns an infinite sequential ordered {@code Stream} produced by iterative 1002 * application of a function {@code f} to an initial element {@code seed}, 1003 * producing a {@code Stream} consisting of {@code seed}, {@code f(seed)}, 1004 * {@code f(f(seed))}, etc. 1005 * 1006 * <p>The first element (position {@code 0}) in the {@code Stream} will be 1007 * the provided {@code seed}. For {@code n > 0}, the element at position 1008 * {@code n}, will be the result of applying the function {@code f} to the 1009 * element at position {@code n - 1}. 1010 * 1011 * @param <T> the type of stream elements 1012 * @param seed the initial element 1013 * @param f a function to be applied to to the previous element to produce 1014 * a new element 1015 * @return a new sequential {@code Stream} 1016 */ iterate(final T seed, final UnaryOperator<T> f)1017 public static<T> Stream<T> iterate(final T seed, final UnaryOperator<T> f) { 1018 Objects.requireNonNull(f); 1019 final Iterator<T> iterator = new Iterator<T>() { 1020 @SuppressWarnings("unchecked") 1021 T t = (T) Streams.NONE; 1022 1023 @Override 1024 public boolean hasNext() { 1025 return true; 1026 } 1027 1028 @Override 1029 public T next() { 1030 return t = (t == Streams.NONE) ? seed : f.apply(t); 1031 } 1032 }; 1033 return StreamSupport.stream(Spliterators.spliteratorUnknownSize( 1034 iterator, 1035 Spliterator.ORDERED | Spliterator.IMMUTABLE), false); 1036 } 1037 1038 /** 1039 * Returns an infinite sequential unordered stream where each element is 1040 * generated by the provided {@code Supplier}. This is suitable for 1041 * generating constant streams, streams of random elements, etc. 1042 * 1043 * @param <T> the type of stream elements 1044 * @param s the {@code Supplier} of generated elements 1045 * @return a new infinite sequential unordered {@code Stream} 1046 */ generate(Supplier<T> s)1047 public static<T> Stream<T> generate(Supplier<T> s) { 1048 Objects.requireNonNull(s); 1049 return StreamSupport.stream( 1050 new StreamSpliterators.InfiniteSupplyingSpliterator.OfRef<>(Long.MAX_VALUE, s), false); 1051 } 1052 1053 /** 1054 * Creates a lazily concatenated stream whose elements are all the 1055 * elements of the first stream followed by all the elements of the 1056 * second stream. The resulting stream is ordered if both 1057 * of the input streams are ordered, and parallel if either of the input 1058 * streams is parallel. When the resulting stream is closed, the close 1059 * handlers for both input streams are invoked. 1060 * 1061 * @implNote 1062 * Use caution when constructing streams from repeated concatenation. 1063 * Accessing an element of a deeply concatenated stream can result in deep 1064 * call chains, or even {@code StackOverflowException}. 1065 * 1066 * @param <T> The type of stream elements 1067 * @param a the first stream 1068 * @param b the second stream 1069 * @return the concatenation of the two input streams 1070 */ concat(Stream<? extends T> a, Stream<? extends T> b)1071 public static <T> Stream<T> concat(Stream<? extends T> a, Stream<? extends T> b) { 1072 Objects.requireNonNull(a); 1073 Objects.requireNonNull(b); 1074 1075 @SuppressWarnings("unchecked") 1076 Spliterator<T> split = new Streams.ConcatSpliterator.OfRef<>( 1077 (Spliterator<T>) a.spliterator(), (Spliterator<T>) b.spliterator()); 1078 Stream<T> stream = StreamSupport.stream(split, a.isParallel() || b.isParallel()); 1079 return stream.onClose(Streams.composedClose(a, b)); 1080 } 1081 1082 /** 1083 * A mutable builder for a {@code Stream}. This allows the creation of a 1084 * {@code Stream} by generating elements individually and adding them to the 1085 * {@code Builder} (without the copying overhead that comes from using 1086 * an {@code ArrayList} as a temporary buffer.) 1087 * 1088 * <p>A stream builder has a lifecycle, which starts in a building 1089 * phase, during which elements can be added, and then transitions to a built 1090 * phase, after which elements may not be added. The built phase begins 1091 * when the {@link #build()} method is called, which creates an ordered 1092 * {@code Stream} whose elements are the elements that were added to the stream 1093 * builder, in the order they were added. 1094 * 1095 * @param <T> the type of stream elements 1096 * @see Stream#builder() 1097 * @since 1.8 1098 */ 1099 public interface Builder<T> extends Consumer<T> { 1100 1101 /** 1102 * Adds an element to the stream being built. 1103 * 1104 * @throws IllegalStateException if the builder has already transitioned to 1105 * the built state 1106 */ 1107 @Override accept(T t)1108 void accept(T t); 1109 1110 /** 1111 * Adds an element to the stream being built. 1112 * 1113 * @implSpec 1114 * The default implementation behaves as if: 1115 * <pre>{@code 1116 * accept(t) 1117 * return this; 1118 * }</pre> 1119 * 1120 * @param t the element to add 1121 * @return {@code this} builder 1122 * @throws IllegalStateException if the builder has already transitioned to 1123 * the built state 1124 */ add(T t)1125 default Builder<T> add(T t) { 1126 accept(t); 1127 return this; 1128 } 1129 1130 /** 1131 * Builds the stream, transitioning this builder to the built state. 1132 * An {@code IllegalStateException} is thrown if there are further attempts 1133 * to operate on the builder after it has entered the built state. 1134 * 1135 * @return the built stream 1136 * @throws IllegalStateException if the builder has already transitioned to 1137 * the built state 1138 */ build()1139 Stream<T> build(); 1140 1141 } 1142 } 1143