1 /* 2 * Copyright (c) 2012, 2017, 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.file.Files; 28 import java.nio.file.Path; 29 import java.util.Arrays; 30 import java.util.Collection; 31 import java.util.Comparator; 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>A stream implementation is permitted significant latitude in optimizing 86 * the computation of the result. For example, a stream implementation is free 87 * to elide operations (or entire stages) from a stream pipeline -- and 88 * therefore elide invocation of behavioral parameters -- if it can prove that 89 * it would not affect the result of the computation. This means that 90 * side-effects of behavioral parameters may not always be executed and should 91 * not be relied upon, unless otherwise specified (such as by the terminal 92 * operations {@code forEach} and {@code forEachOrdered}). (For a specific 93 * example of such an optimization, see the API note documented on the 94 * {@link #count} operation. For more detail, see the 95 * <a href="package-summary.html#SideEffects">side-effects</a> section of the 96 * stream package documentation.) 97 * 98 * <p>Collections and streams, while bearing some superficial similarities, 99 * have different goals. Collections are primarily concerned with the efficient 100 * management of, and access to, their elements. By contrast, streams do not 101 * provide a means to directly access or manipulate their elements, and are 102 * instead concerned with declaratively describing their source and the 103 * computational operations which will be performed in aggregate on that source. 104 * However, if the provided stream operations do not offer the desired 105 * functionality, the {@link #iterator()} and {@link #spliterator()} operations 106 * can be used to perform a controlled traversal. 107 * 108 * <p>A stream pipeline, like the "widgets" example above, can be viewed as 109 * a <em>query</em> on the stream source. Unless the source was explicitly 110 * designed for concurrent modification (such as a {@link ConcurrentHashMap}), 111 * unpredictable or erroneous behavior may result from modifying the stream 112 * source while it is being queried. 113 * 114 * <p>Most stream operations accept parameters that describe user-specified 115 * behavior, such as the lambda expression {@code w -> w.getWeight()} passed to 116 * {@code mapToInt} in the example above. To preserve correct behavior, 117 * these <em>behavioral parameters</em>: 118 * <ul> 119 * <li>must be <a href="package-summary.html#NonInterference">non-interfering</a> 120 * (they do not modify the stream source); and</li> 121 * <li>in most cases must be <a href="package-summary.html#Statelessness">stateless</a> 122 * (their result should not depend on any state that might change during execution 123 * of the stream pipeline).</li> 124 * </ul> 125 * 126 * <p>Such parameters are always instances of a 127 * <a href="../function/package-summary.html">functional interface</a> such 128 * as {@link java.util.function.Function}, and are often lambda expressions or 129 * method references. Unless otherwise specified these parameters must be 130 * <em>non-null</em>. 131 * 132 * <p>A stream should be operated on (invoking an intermediate or terminal stream 133 * operation) only once. This rules out, for example, "forked" streams, where 134 * the same source feeds two or more pipelines, or multiple traversals of the 135 * same stream. A stream implementation may throw {@link IllegalStateException} 136 * if it detects that the stream is being reused. However, since some stream 137 * operations may return their receiver rather than a new stream object, it may 138 * not be possible to detect reuse in all cases. 139 * 140 * <p>Streams have a {@link #close()} method and implement {@link AutoCloseable}. 141 * Operating on a stream after it has been closed will throw {@link IllegalStateException}. 142 * Most stream instances do not actually need to be closed after use, as they 143 * are backed by collections, arrays, or generating functions, which require no 144 * special resource management. Generally, only streams whose source is an IO channel, 145 * such as those returned by {@link Files#lines(Path)}, will require closing. If a 146 * stream does require closing, it must be opened as a resource within a try-with-resources 147 * statement or similar control structure to ensure that it is closed promptly after its 148 * operations have completed. 149 * 150 * <p>Stream pipelines may execute either sequentially or in 151 * <a href="package-summary.html#Parallelism">parallel</a>. This 152 * execution mode is a property of the stream. Streams are created 153 * with an initial choice of sequential or parallel execution. (For example, 154 * {@link Collection#stream() Collection.stream()} creates a sequential stream, 155 * and {@link Collection#parallelStream() Collection.parallelStream()} creates 156 * a parallel one.) This choice of execution mode may be modified by the 157 * {@link #sequential()} or {@link #parallel()} methods, and may be queried with 158 * the {@link #isParallel()} method. 159 * 160 * @param <T> the type of the stream elements 161 * @since 1.8 162 * @see IntStream 163 * @see LongStream 164 * @see DoubleStream 165 * @see <a href="package-summary.html">java.util.stream</a> 166 */ 167 public interface Stream<T> extends BaseStream<T, Stream<T>> { 168 169 /** 170 * Returns a stream consisting of the elements of this stream that match 171 * the given predicate. 172 * 173 * <p>This is an <a href="package-summary.html#StreamOps">intermediate 174 * operation</a>. 175 * 176 * @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>, 177 * <a href="package-summary.html#Statelessness">stateless</a> 178 * predicate to apply to each element to determine if it 179 * should be included 180 * @return the new stream 181 */ 182 Stream<T> filter(Predicate<? super T> predicate); 183 184 /** 185 * Returns a stream consisting of the results of applying the given 186 * 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 <R> The element type of the new stream 192 * @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>, 193 * <a href="package-summary.html#Statelessness">stateless</a> 194 * function to apply to each element 195 * @return the new stream 196 */ 197 <R> Stream<R> map(Function<? super T, ? extends R> mapper); 198 199 /** 200 * Returns an {@code IntStream} consisting of the results of applying the 201 * given function to the elements of this stream. 202 * 203 * <p>This is an <a href="package-summary.html#StreamOps"> 204 * intermediate operation</a>. 205 * 206 * @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>, 207 * <a href="package-summary.html#Statelessness">stateless</a> 208 * function to apply to each element 209 * @return the new stream 210 */ 211 IntStream mapToInt(ToIntFunction<? super T> mapper); 212 213 /** 214 * Returns a {@code LongStream} consisting of the results of applying the 215 * given function to the elements of this stream. 216 * 217 * <p>This is an <a href="package-summary.html#StreamOps">intermediate 218 * operation</a>. 219 * 220 * @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>, 221 * <a href="package-summary.html#Statelessness">stateless</a> 222 * function to apply to each element 223 * @return the new stream 224 */ 225 LongStream mapToLong(ToLongFunction<? super T> mapper); 226 227 /** 228 * Returns a {@code DoubleStream} consisting of the results of applying the 229 * given function to the elements of this stream. 230 * 231 * <p>This is an <a href="package-summary.html#StreamOps">intermediate 232 * operation</a>. 233 * 234 * @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>, 235 * <a href="package-summary.html#Statelessness">stateless</a> 236 * function to apply to each element 237 * @return the new stream 238 */ 239 DoubleStream mapToDouble(ToDoubleFunction<? super T> mapper); 240 241 /** 242 * Returns a stream consisting of the results of replacing each element of 243 * this stream with the contents of a mapped stream produced by applying 244 * the provided mapping function to each element. Each mapped stream is 245 * {@link java.util.stream.BaseStream#close() closed} after its contents 246 * have been placed into this stream. (If a mapped stream is {@code null} 247 * an empty stream is used, instead.) 248 * 249 * <p>This is an <a href="package-summary.html#StreamOps">intermediate 250 * operation</a>. 251 * 252 * @apiNote 253 * The {@code flatMap()} operation has the effect of applying a one-to-many 254 * transformation to the elements of the stream, and then flattening the 255 * resulting elements into a new stream. 256 * 257 * <p><b>Examples.</b> 258 * 259 * <p>If {@code orders} is a stream of purchase orders, and each purchase 260 * order contains a collection of line items, then the following produces a 261 * stream containing all the line items in all the orders: 262 * <pre>{@code 263 * orders.flatMap(order -> order.getLineItems().stream())... 264 * }</pre> 265 * 266 * <p>If {@code path} is the path to a file, then the following produces a 267 * stream of the {@code words} contained in that file: 268 * <pre>{@code 269 * Stream<String> lines = Files.lines(path, StandardCharsets.UTF_8); 270 * Stream<String> words = lines.flatMap(line -> Stream.of(line.split(" +"))); 271 * }</pre> 272 * The {@code mapper} function passed to {@code flatMap} splits a line, 273 * using a simple regular expression, into an array of words, and then 274 * creates a stream of words from that array. 275 * 276 * @param <R> The element type of the new stream 277 * @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>, 278 * <a href="package-summary.html#Statelessness">stateless</a> 279 * function to apply to each element which produces a stream 280 * of new values 281 * @return the new stream 282 */ 283 <R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper); 284 285 /** 286 * Returns an {@code IntStream} consisting of the results of replacing each 287 * element of this stream with the contents of a mapped stream produced by 288 * applying the provided mapping function to each element. Each mapped 289 * stream is {@link java.util.stream.BaseStream#close() closed} after its 290 * contents have been placed into this stream. (If a mapped stream is 291 * {@code null} an empty stream is used, instead.) 292 * 293 * <p>This is an <a href="package-summary.html#StreamOps">intermediate 294 * operation</a>. 295 * 296 * @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>, 297 * <a href="package-summary.html#Statelessness">stateless</a> 298 * function to apply to each element which produces a stream 299 * of new values 300 * @return the new stream 301 * @see #flatMap(Function) 302 */ 303 IntStream flatMapToInt(Function<? super T, ? extends IntStream> mapper); 304 305 /** 306 * Returns an {@code LongStream} consisting of the results of replacing each 307 * element of this stream with the contents of a mapped stream produced by 308 * applying the provided mapping function to each element. Each mapped 309 * stream is {@link java.util.stream.BaseStream#close() closed} after its 310 * contents have been placed into this stream. (If a mapped stream is 311 * {@code null} an empty stream is used, instead.) 312 * 313 * <p>This is an <a href="package-summary.html#StreamOps">intermediate 314 * operation</a>. 315 * 316 * @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>, 317 * <a href="package-summary.html#Statelessness">stateless</a> 318 * function to apply to each element which produces a stream 319 * of new values 320 * @return the new stream 321 * @see #flatMap(Function) 322 */ 323 LongStream flatMapToLong(Function<? super T, ? extends LongStream> mapper); 324 325 /** 326 * Returns an {@code DoubleStream} consisting of the results of replacing 327 * each element of this stream with the contents of a mapped stream produced 328 * by applying the provided mapping function to each element. Each mapped 329 * stream is {@link java.util.stream.BaseStream#close() closed} after its 330 * contents have placed been into this stream. (If a mapped stream is 331 * {@code null} an empty stream is used, instead.) 332 * 333 * <p>This is an <a href="package-summary.html#StreamOps">intermediate 334 * operation</a>. 335 * 336 * @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>, 337 * <a href="package-summary.html#Statelessness">stateless</a> 338 * function to apply to each element which produces a stream 339 * of new values 340 * @return the new stream 341 * @see #flatMap(Function) 342 */ 343 DoubleStream flatMapToDouble(Function<? super T, ? extends DoubleStream> mapper); 344 345 /** 346 * Returns a stream consisting of the distinct elements (according to 347 * {@link Object#equals(Object)}) of this stream. 348 * 349 * <p>For ordered streams, the selection of distinct elements is stable 350 * (for duplicated elements, the element appearing first in the encounter 351 * order is preserved.) For unordered streams, no stability guarantees 352 * are made. 353 * 354 * <p>This is a <a href="package-summary.html#StreamOps">stateful 355 * intermediate operation</a>. 356 * 357 * @apiNote 358 * Preserving stability for {@code distinct()} in parallel pipelines is 359 * relatively expensive (requires that the operation act as a full barrier, 360 * with substantial buffering overhead), and stability is often not needed. 361 * Using an unordered stream source (such as {@link #generate(Supplier)}) 362 * or removing the ordering constraint with {@link #unordered()} may result 363 * in significantly more efficient execution for {@code distinct()} in parallel 364 * pipelines, if the semantics of your situation permit. If consistency 365 * with encounter order is required, and you are experiencing poor performance 366 * or memory utilization with {@code distinct()} in parallel pipelines, 367 * switching to sequential execution with {@link #sequential()} may improve 368 * performance. 369 * 370 * @return the new stream 371 */ 372 Stream<T> distinct(); 373 374 /** 375 * Returns a stream consisting of the elements of this stream, sorted 376 * according to natural order. If the elements of this stream are not 377 * {@code Comparable}, a {@code java.lang.ClassCastException} may be thrown 378 * when the terminal operation is executed. 379 * 380 * <p>For ordered streams, the sort is stable. For unordered streams, no 381 * stability guarantees are made. 382 * 383 * <p>This is a <a href="package-summary.html#StreamOps">stateful 384 * intermediate operation</a>. 385 * 386 * @return the new stream 387 */ 388 Stream<T> sorted(); 389 390 /** 391 * Returns a stream consisting of the elements of this stream, sorted 392 * according to the provided {@code Comparator}. 393 * 394 * <p>For ordered streams, the sort is stable. For unordered streams, no 395 * stability guarantees are made. 396 * 397 * <p>This is a <a href="package-summary.html#StreamOps">stateful 398 * intermediate operation</a>. 399 * 400 * @param comparator a <a href="package-summary.html#NonInterference">non-interfering</a>, 401 * <a href="package-summary.html#Statelessness">stateless</a> 402 * {@code Comparator} to be used to compare stream elements 403 * @return the new stream 404 */ 405 Stream<T> sorted(Comparator<? super T> comparator); 406 407 /** 408 * Returns a stream consisting of the elements of this stream, additionally 409 * performing the provided action on each element as elements are consumed 410 * from the resulting stream. 411 * 412 * <p>This is an <a href="package-summary.html#StreamOps">intermediate 413 * operation</a>. 414 * 415 * <p>For parallel stream pipelines, the action may be called at 416 * whatever time and in whatever thread the element is made available by the 417 * upstream operation. If the action modifies shared state, 418 * it is responsible for providing the required synchronization. 419 * 420 * @apiNote This method exists mainly to support debugging, where you want 421 * to see the elements as they flow past a certain point in a pipeline: 422 * <pre>{@code 423 * Stream.of("one", "two", "three", "four") 424 * .filter(e -> e.length() > 3) 425 * .peek(e -> System.out.println("Filtered value: " + e)) 426 * .map(String::toUpperCase) 427 * .peek(e -> System.out.println("Mapped value: " + e)) 428 * .collect(Collectors.toList()); 429 * }</pre> 430 * 431 * <p>In cases where the stream implementation is able to optimize away the 432 * production of some or all the elements (such as with short-circuiting 433 * operations like {@code findFirst}, or in the example described in 434 * {@link #count}), the action will not be invoked for those elements. 435 * 436 * @param action a <a href="package-summary.html#NonInterference"> 437 * non-interfering</a> action to perform on the elements as 438 * they are consumed from the stream 439 * @return the new stream 440 */ 441 Stream<T> peek(Consumer<? super T> action); 442 443 /** 444 * Returns a stream consisting of the elements of this stream, truncated 445 * to be no longer than {@code maxSize} in length. 446 * 447 * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting 448 * stateful intermediate operation</a>. 449 * 450 * @apiNote 451 * While {@code limit()} is generally a cheap operation on sequential 452 * stream pipelines, it can be quite expensive on ordered parallel pipelines, 453 * especially for large values of {@code maxSize}, since {@code limit(n)} 454 * is constrained to return not just any <em>n</em> elements, but the 455 * <em>first n</em> elements in the encounter order. Using an unordered 456 * stream source (such as {@link #generate(Supplier)}) or removing the 457 * ordering constraint with {@link #unordered()} may result in significant 458 * speedups of {@code limit()} in parallel pipelines, if the semantics of 459 * your situation permit. If consistency with encounter order is required, 460 * and you are experiencing poor performance or memory utilization with 461 * {@code limit()} in parallel pipelines, switching to sequential execution 462 * with {@link #sequential()} may improve performance. 463 * 464 * @param maxSize the number of elements the stream should be limited to 465 * @return the new stream 466 * @throws IllegalArgumentException if {@code maxSize} is negative 467 */ 468 Stream<T> limit(long maxSize); 469 470 /** 471 * Returns a stream consisting of the remaining elements of this stream 472 * after discarding the first {@code n} elements of the stream. 473 * If this stream contains fewer than {@code n} elements then an 474 * empty stream will be returned. 475 * 476 * <p>This is a <a href="package-summary.html#StreamOps">stateful 477 * intermediate operation</a>. 478 * 479 * @apiNote 480 * While {@code skip()} is generally a cheap operation on sequential 481 * stream pipelines, it can be quite expensive on ordered parallel pipelines, 482 * especially for large values of {@code n}, since {@code skip(n)} 483 * is constrained to skip not just any <em>n</em> elements, but the 484 * <em>first n</em> elements in the encounter order. Using an unordered 485 * stream source (such as {@link #generate(Supplier)}) or removing the 486 * ordering constraint with {@link #unordered()} may result in significant 487 * speedups of {@code skip()} in parallel pipelines, if the semantics of 488 * your situation permit. If consistency with encounter order is required, 489 * and you are experiencing poor performance or memory utilization with 490 * {@code skip()} in parallel pipelines, switching to sequential execution 491 * with {@link #sequential()} may improve performance. 492 * 493 * @param n the number of leading elements to skip 494 * @return the new stream 495 * @throws IllegalArgumentException if {@code n} is negative 496 */ 497 Stream<T> skip(long n); 498 499 /** 500 * Returns, if this stream is ordered, a stream consisting of the longest 501 * prefix of elements taken from this stream that match the given predicate. 502 * Otherwise returns, if this stream is unordered, a stream consisting of a 503 * subset of elements taken from this stream that match the given predicate. 504 * 505 * <p>If this stream is ordered then the longest prefix is a contiguous 506 * sequence of elements of this stream that match the given predicate. The 507 * first element of the sequence is the first element of this stream, and 508 * the element immediately following the last element of the sequence does 509 * not match the given predicate. 510 * 511 * <p>If this stream is unordered, and some (but not all) elements of this 512 * stream match the given predicate, then the behavior of this operation is 513 * nondeterministic; it is free to take any subset of matching elements 514 * (which includes the empty set). 515 * 516 * <p>Independent of whether this stream is ordered or unordered if all 517 * elements of this stream match the given predicate then this operation 518 * takes all elements (the result is the same as the input), or if no 519 * elements of the stream match the given predicate then no elements are 520 * taken (the result is an empty stream). 521 * 522 * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting 523 * stateful intermediate operation</a>. 524 * 525 * @implSpec 526 * The default implementation obtains the {@link #spliterator() spliterator} 527 * of this stream, wraps that spliterator so as to support the semantics 528 * of this operation on traversal, and returns a new stream associated with 529 * the wrapped spliterator. The returned stream preserves the execution 530 * characteristics of this stream (namely parallel or sequential execution 531 * as per {@link #isParallel()}) but the wrapped spliterator may choose to 532 * not support splitting. When the returned stream is closed, the close 533 * handlers for both the returned and this stream are invoked. 534 * 535 * @apiNote 536 * While {@code takeWhile()} is generally a cheap operation on sequential 537 * stream pipelines, it can be quite expensive on ordered parallel 538 * pipelines, since the operation is constrained to return not just any 539 * valid prefix, but the longest prefix of elements in the encounter order. 540 * Using an unordered stream source (such as {@link #generate(Supplier)}) or 541 * removing the ordering constraint with {@link #unordered()} may result in 542 * significant speedups of {@code takeWhile()} in parallel pipelines, if the 543 * semantics of your situation permit. If consistency with encounter order 544 * is required, and you are experiencing poor performance or memory 545 * utilization with {@code takeWhile()} in parallel pipelines, switching to 546 * sequential execution with {@link #sequential()} may improve performance. 547 * 548 * @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>, 549 * <a href="package-summary.html#Statelessness">stateless</a> 550 * predicate to apply to elements to determine the longest 551 * prefix of elements. 552 * @return the new stream 553 * @since 9 554 */ 555 default Stream<T> takeWhile(Predicate<? super T> predicate) { 556 Objects.requireNonNull(predicate); 557 // Reuses the unordered spliterator, which, when encounter is present, 558 // is safe to use as long as it configured not to split 559 return StreamSupport.stream( 560 new WhileOps.UnorderedWhileSpliterator.OfRef.Taking<>(spliterator(), true, predicate), 561 isParallel()).onClose(this::close); 562 } 563 564 /** 565 * Returns, if this stream is ordered, a stream consisting of the remaining 566 * elements of this stream after dropping the longest prefix of elements 567 * that match the given predicate. Otherwise returns, if this stream is 568 * unordered, a stream consisting of the remaining elements of this stream 569 * after dropping a subset of elements that match the given predicate. 570 * 571 * <p>If this stream is ordered then the longest prefix is a contiguous 572 * sequence of elements of this stream that match the given predicate. The 573 * first element of the sequence is the first element of this stream, and 574 * the element immediately following the last element of the sequence does 575 * not match the given predicate. 576 * 577 * <p>If this stream is unordered, and some (but not all) elements of this 578 * stream match the given predicate, then the behavior of this operation is 579 * nondeterministic; it is free to drop any subset of matching elements 580 * (which includes the empty set). 581 * 582 * <p>Independent of whether this stream is ordered or unordered if all 583 * elements of this stream match the given predicate then this operation 584 * drops all elements (the result is an empty stream), or if no elements of 585 * the stream match the given predicate then no elements are dropped (the 586 * result is the same as the input). 587 * 588 * <p>This is a <a href="package-summary.html#StreamOps">stateful 589 * intermediate operation</a>. 590 * 591 * @implSpec 592 * The default implementation obtains the {@link #spliterator() spliterator} 593 * of this stream, wraps that spliterator so as to support the semantics 594 * of this operation on traversal, and returns a new stream associated with 595 * the wrapped spliterator. The returned stream preserves the execution 596 * characteristics of this stream (namely parallel or sequential execution 597 * as per {@link #isParallel()}) but the wrapped spliterator may choose to 598 * not support splitting. When the returned stream is closed, the close 599 * handlers for both the returned and this stream are invoked. 600 * 601 * @apiNote 602 * While {@code dropWhile()} is generally a cheap operation on sequential 603 * stream pipelines, it can be quite expensive on ordered parallel 604 * pipelines, since the operation is constrained to return not just any 605 * valid prefix, but the longest prefix of elements in the encounter order. 606 * Using an unordered stream source (such as {@link #generate(Supplier)}) or 607 * removing the ordering constraint with {@link #unordered()} may result in 608 * significant speedups of {@code dropWhile()} in parallel pipelines, if the 609 * semantics of your situation permit. If consistency with encounter order 610 * is required, and you are experiencing poor performance or memory 611 * utilization with {@code dropWhile()} in parallel pipelines, switching to 612 * sequential execution with {@link #sequential()} may improve performance. 613 * 614 * @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>, 615 * <a href="package-summary.html#Statelessness">stateless</a> 616 * predicate to apply to elements to determine the longest 617 * prefix of elements. 618 * @return the new stream 619 * @since 9 620 */ 621 default Stream<T> dropWhile(Predicate<? super T> predicate) { 622 Objects.requireNonNull(predicate); 623 // Reuses the unordered spliterator, which, when encounter is present, 624 // is safe to use as long as it configured not to split 625 return StreamSupport.stream( 626 new WhileOps.UnorderedWhileSpliterator.OfRef.Dropping<>(spliterator(), true, predicate), 627 isParallel()).onClose(this::close); 628 } 629 630 /** 631 * Performs an action for each element of this stream. 632 * 633 * <p>This is a <a href="package-summary.html#StreamOps">terminal 634 * operation</a>. 635 * 636 * <p>The behavior of this operation is explicitly nondeterministic. 637 * For parallel stream pipelines, this operation does <em>not</em> 638 * guarantee to respect the encounter order of the stream, as doing so 639 * would sacrifice the benefit of parallelism. For any given element, the 640 * action may be performed at whatever time and in whatever thread the 641 * library chooses. If the action accesses shared state, it is 642 * responsible for providing the required synchronization. 643 * 644 * @param action a <a href="package-summary.html#NonInterference"> 645 * non-interfering</a> action to perform on the elements 646 */ 647 void forEach(Consumer<? super T> action); 648 649 /** 650 * Performs an action for each element of this stream, in the encounter 651 * order of the stream if the stream has a defined encounter order. 652 * 653 * <p>This is a <a href="package-summary.html#StreamOps">terminal 654 * operation</a>. 655 * 656 * <p>This operation processes the elements one at a time, in encounter 657 * order if one exists. Performing the action for one element 658 * <a href="../concurrent/package-summary.html#MemoryVisibility"><i>happens-before</i></a> 659 * performing the action for subsequent elements, but for any given element, 660 * the action may be performed in whatever thread the library chooses. 661 * 662 * @param action a <a href="package-summary.html#NonInterference"> 663 * non-interfering</a> action to perform on the elements 664 * @see #forEach(Consumer) 665 */ 666 void forEachOrdered(Consumer<? super T> action); 667 668 /** 669 * Returns an array containing the elements of this stream. 670 * 671 * <p>This is a <a href="package-summary.html#StreamOps">terminal 672 * operation</a>. 673 * 674 * @return an array, whose {@linkplain Class#getComponentType runtime component 675 * type} is {@code Object}, containing the elements of this stream 676 */ 677 Object[] toArray(); 678 679 /** 680 * Returns an array containing the elements of this stream, using the 681 * provided {@code generator} function to allocate the returned array, as 682 * well as any additional arrays that might be required for a partitioned 683 * execution or for resizing. 684 * 685 * <p>This is a <a href="package-summary.html#StreamOps">terminal 686 * operation</a>. 687 * 688 * @apiNote 689 * The generator function takes an integer, which is the size of the 690 * desired array, and produces an array of the desired size. This can be 691 * concisely expressed with an array constructor reference: 692 * <pre>{@code 693 * Person[] men = people.stream() 694 * .filter(p -> p.getGender() == MALE) 695 * .toArray(Person[]::new); 696 * }</pre> 697 * 698 * @param <A> the component type of the resulting array 699 * @param generator a function which produces a new array of the desired 700 * type and the provided length 701 * @return an array containing the elements in this stream 702 * @throws ArrayStoreException if the runtime type of any element of this 703 * stream is not assignable to the {@linkplain Class#getComponentType 704 * runtime component type} of the generated array 705 */ 706 <A> A[] toArray(IntFunction<A[]> generator); 707 708 /** 709 * Performs a <a href="package-summary.html#Reduction">reduction</a> on the 710 * elements of this stream, using the provided identity value and an 711 * <a href="package-summary.html#Associativity">associative</a> 712 * accumulation function, and returns the reduced value. This is equivalent 713 * to: 714 * <pre>{@code 715 * T result = identity; 716 * for (T element : this stream) 717 * result = accumulator.apply(result, element) 718 * return result; 719 * }</pre> 720 * 721 * but is not constrained to execute sequentially. 722 * 723 * <p>The {@code identity} value must be an identity for the accumulator 724 * function. This means that for all {@code t}, 725 * {@code accumulator.apply(identity, t)} is equal to {@code t}. 726 * The {@code accumulator} function must be an 727 * <a href="package-summary.html#Associativity">associative</a> function. 728 * 729 * <p>This is a <a href="package-summary.html#StreamOps">terminal 730 * operation</a>. 731 * 732 * @apiNote Sum, min, max, average, and string concatenation are all special 733 * cases of reduction. Summing a stream of numbers can be expressed as: 734 * 735 * <pre>{@code 736 * Integer sum = integers.reduce(0, (a, b) -> a+b); 737 * }</pre> 738 * 739 * or: 740 * 741 * <pre>{@code 742 * Integer sum = integers.reduce(0, Integer::sum); 743 * }</pre> 744 * 745 * <p>While this may seem a more roundabout way to perform an aggregation 746 * compared to simply mutating a running total in a loop, reduction 747 * operations parallelize more gracefully, without needing additional 748 * synchronization and with greatly reduced risk of data races. 749 * 750 * @param identity the identity value for the accumulating function 751 * @param accumulator an <a href="package-summary.html#Associativity">associative</a>, 752 * <a href="package-summary.html#NonInterference">non-interfering</a>, 753 * <a href="package-summary.html#Statelessness">stateless</a> 754 * function for combining two values 755 * @return the result of the reduction 756 */ 757 T reduce(T identity, BinaryOperator<T> accumulator); 758 759 /** 760 * Performs a <a href="package-summary.html#Reduction">reduction</a> on the 761 * elements of this stream, using an 762 * <a href="package-summary.html#Associativity">associative</a> accumulation 763 * function, and returns an {@code Optional} describing the reduced value, 764 * if any. This is equivalent to: 765 * <pre>{@code 766 * boolean foundAny = false; 767 * T result = null; 768 * for (T element : this stream) { 769 * if (!foundAny) { 770 * foundAny = true; 771 * result = element; 772 * } 773 * else 774 * result = accumulator.apply(result, element); 775 * } 776 * return foundAny ? Optional.of(result) : Optional.empty(); 777 * }</pre> 778 * 779 * but is not constrained to execute sequentially. 780 * 781 * <p>The {@code accumulator} function must be an 782 * <a href="package-summary.html#Associativity">associative</a> function. 783 * 784 * <p>This is a <a href="package-summary.html#StreamOps">terminal 785 * operation</a>. 786 * 787 * @param accumulator an <a href="package-summary.html#Associativity">associative</a>, 788 * <a href="package-summary.html#NonInterference">non-interfering</a>, 789 * <a href="package-summary.html#Statelessness">stateless</a> 790 * function for combining two values 791 * @return an {@link Optional} describing the result of the reduction 792 * @throws NullPointerException if the result of the reduction is null 793 * @see #reduce(Object, BinaryOperator) 794 * @see #min(Comparator) 795 * @see #max(Comparator) 796 */ 797 Optional<T> reduce(BinaryOperator<T> accumulator); 798 799 /** 800 * Performs a <a href="package-summary.html#Reduction">reduction</a> on the 801 * elements of this stream, using the provided identity, accumulation and 802 * combining functions. This is equivalent to: 803 * <pre>{@code 804 * U result = identity; 805 * for (T element : this stream) 806 * result = accumulator.apply(result, element) 807 * return result; 808 * }</pre> 809 * 810 * but is not constrained to execute sequentially. 811 * 812 * <p>The {@code identity} value must be an identity for the combiner 813 * function. This means that for all {@code u}, {@code combiner(identity, u)} 814 * is equal to {@code u}. Additionally, the {@code combiner} function 815 * must be compatible with the {@code accumulator} function; for all 816 * {@code u} and {@code t}, the following must hold: 817 * <pre>{@code 818 * combiner.apply(u, accumulator.apply(identity, t)) == accumulator.apply(u, t) 819 * }</pre> 820 * 821 * <p>This is a <a href="package-summary.html#StreamOps">terminal 822 * operation</a>. 823 * 824 * @apiNote Many reductions using this form can be represented more simply 825 * by an explicit combination of {@code map} and {@code reduce} operations. 826 * The {@code accumulator} function acts as a fused mapper and accumulator, 827 * which can sometimes be more efficient than separate mapping and reduction, 828 * such as when knowing the previously reduced value allows you to avoid 829 * some computation. 830 * 831 * @param <U> The type of the result 832 * @param identity the identity value for the combiner function 833 * @param accumulator an <a href="package-summary.html#Associativity">associative</a>, 834 * <a href="package-summary.html#NonInterference">non-interfering</a>, 835 * <a href="package-summary.html#Statelessness">stateless</a> 836 * function for incorporating an additional element into a result 837 * @param combiner an <a href="package-summary.html#Associativity">associative</a>, 838 * <a href="package-summary.html#NonInterference">non-interfering</a>, 839 * <a href="package-summary.html#Statelessness">stateless</a> 840 * function for combining two values, which must be 841 * compatible with the accumulator function 842 * @return the result of the reduction 843 * @see #reduce(BinaryOperator) 844 * @see #reduce(Object, BinaryOperator) 845 */ 846 <U> U reduce(U identity, 847 BiFunction<U, ? super T, U> accumulator, 848 BinaryOperator<U> combiner); 849 850 /** 851 * Performs a <a href="package-summary.html#MutableReduction">mutable 852 * reduction</a> operation on the elements of this stream. A mutable 853 * reduction is one in which the reduced value is a mutable result container, 854 * such as an {@code ArrayList}, and elements are incorporated by updating 855 * the state of the result rather than by replacing the result. This 856 * produces a result equivalent to: 857 * <pre>{@code 858 * R result = supplier.get(); 859 * for (T element : this stream) 860 * accumulator.accept(result, element); 861 * return result; 862 * }</pre> 863 * 864 * <p>Like {@link #reduce(Object, BinaryOperator)}, {@code collect} operations 865 * can be parallelized without requiring additional synchronization. 866 * 867 * <p>This is a <a href="package-summary.html#StreamOps">terminal 868 * operation</a>. 869 * 870 * @apiNote There are many existing classes in the JDK whose signatures are 871 * well-suited for use with method references as arguments to {@code collect()}. 872 * For example, the following will accumulate strings into an {@code ArrayList}: 873 * <pre>{@code 874 * List<String> asList = stringStream.collect(ArrayList::new, ArrayList::add, 875 * ArrayList::addAll); 876 * }</pre> 877 * 878 * <p>The following will take a stream of strings and concatenates them into a 879 * single string: 880 * <pre>{@code 881 * String concat = stringStream.collect(StringBuilder::new, StringBuilder::append, 882 * StringBuilder::append) 883 * .toString(); 884 * }</pre> 885 * 886 * @param <R> the type of the mutable result container 887 * @param supplier a function that creates a new mutable result container. 888 * For a parallel execution, this function may be called 889 * multiple times and must return a fresh value each time. 890 * @param accumulator an <a href="package-summary.html#Associativity">associative</a>, 891 * <a href="package-summary.html#NonInterference">non-interfering</a>, 892 * <a href="package-summary.html#Statelessness">stateless</a> 893 * function that must fold an element into a result 894 * container. 895 * @param combiner an <a href="package-summary.html#Associativity">associative</a>, 896 * <a href="package-summary.html#NonInterference">non-interfering</a>, 897 * <a href="package-summary.html#Statelessness">stateless</a> 898 * function that accepts two partial result containers 899 * and merges them, which must be compatible with the 900 * accumulator function. The combiner function must fold 901 * the elements from the second result container into the 902 * first result container. 903 * @return the result of the reduction 904 */ 905 <R> R collect(Supplier<R> supplier, 906 BiConsumer<R, ? super T> accumulator, 907 BiConsumer<R, R> combiner); 908 909 /** 910 * Performs a <a href="package-summary.html#MutableReduction">mutable 911 * reduction</a> operation on the elements of this stream using a 912 * {@code Collector}. A {@code Collector} 913 * encapsulates the functions used as arguments to 914 * {@link #collect(Supplier, BiConsumer, BiConsumer)}, allowing for reuse of 915 * collection strategies and composition of collect operations such as 916 * multiple-level grouping or partitioning. 917 * 918 * <p>If the stream is parallel, and the {@code Collector} 919 * is {@link Collector.Characteristics#CONCURRENT concurrent}, and 920 * either the stream is unordered or the collector is 921 * {@link Collector.Characteristics#UNORDERED unordered}, 922 * then a concurrent reduction will be performed (see {@link Collector} for 923 * details on concurrent reduction.) 924 * 925 * <p>This is a <a href="package-summary.html#StreamOps">terminal 926 * operation</a>. 927 * 928 * <p>When executed in parallel, multiple intermediate results may be 929 * instantiated, populated, and merged so as to maintain isolation of 930 * mutable data structures. Therefore, even when executed in parallel 931 * with non-thread-safe data structures (such as {@code ArrayList}), no 932 * additional synchronization is needed for a parallel reduction. 933 * 934 * @apiNote 935 * The following will accumulate strings into an ArrayList: 936 * <pre>{@code 937 * List<String> asList = stringStream.collect(Collectors.toList()); 938 * }</pre> 939 * 940 * <p>The following will classify {@code Person} objects by city: 941 * <pre>{@code 942 * Map<String, List<Person>> peopleByCity 943 * = personStream.collect(Collectors.groupingBy(Person::getCity)); 944 * }</pre> 945 * 946 * <p>The following will classify {@code Person} objects by state and city, 947 * cascading two {@code Collector}s together: 948 * <pre>{@code 949 * Map<String, Map<String, List<Person>>> peopleByStateAndCity 950 * = personStream.collect(Collectors.groupingBy(Person::getState, 951 * Collectors.groupingBy(Person::getCity))); 952 * }</pre> 953 * 954 * @param <R> the type of the result 955 * @param <A> the intermediate accumulation type of the {@code Collector} 956 * @param collector the {@code Collector} describing the reduction 957 * @return the result of the reduction 958 * @see #collect(Supplier, BiConsumer, BiConsumer) 959 * @see Collectors 960 */ 961 <R, A> R collect(Collector<? super T, A, R> collector); 962 963 /** 964 * Returns the minimum element of this stream according to the provided 965 * {@code Comparator}. This is a special case of a 966 * <a href="package-summary.html#Reduction">reduction</a>. 967 * 968 * <p>This is a <a href="package-summary.html#StreamOps">terminal operation</a>. 969 * 970 * @param comparator a <a href="package-summary.html#NonInterference">non-interfering</a>, 971 * <a href="package-summary.html#Statelessness">stateless</a> 972 * {@code Comparator} to compare elements of this stream 973 * @return an {@code Optional} describing the minimum element of this stream, 974 * or an empty {@code Optional} if the stream is empty 975 * @throws NullPointerException if the minimum element is null 976 */ 977 Optional<T> min(Comparator<? super T> comparator); 978 979 /** 980 * Returns the maximum element of this stream according to the provided 981 * {@code Comparator}. This is a special case of a 982 * <a href="package-summary.html#Reduction">reduction</a>. 983 * 984 * <p>This is a <a href="package-summary.html#StreamOps">terminal 985 * operation</a>. 986 * 987 * @param comparator a <a href="package-summary.html#NonInterference">non-interfering</a>, 988 * <a href="package-summary.html#Statelessness">stateless</a> 989 * {@code Comparator} to compare elements of this stream 990 * @return an {@code Optional} describing the maximum element of this stream, 991 * or an empty {@code Optional} if the stream is empty 992 * @throws NullPointerException if the maximum element is null 993 */ 994 Optional<T> max(Comparator<? super T> comparator); 995 996 /** 997 * Returns the count of elements in this stream. This is a special case of 998 * a <a href="package-summary.html#Reduction">reduction</a> and is 999 * equivalent to: 1000 * <pre>{@code 1001 * return mapToLong(e -> 1L).sum(); 1002 * }</pre> 1003 * 1004 * <p>This is a <a href="package-summary.html#StreamOps">terminal operation</a>. 1005 * 1006 * @apiNote 1007 * An implementation may choose to not execute the stream pipeline (either 1008 * sequentially or in parallel) if it is capable of computing the count 1009 * directly from the stream source. In such cases no source elements will 1010 * be traversed and no intermediate operations will be evaluated. 1011 * Behavioral parameters with side-effects, which are strongly discouraged 1012 * except for harmless cases such as debugging, may be affected. For 1013 * example, consider the following stream: 1014 * <pre>{@code 1015 * List<String> l = Arrays.asList("A", "B", "C", "D"); 1016 * long count = l.stream().peek(System.out::println).count(); 1017 * }</pre> 1018 * The number of elements covered by the stream source, a {@code List}, is 1019 * known and the intermediate operation, {@code peek}, does not inject into 1020 * or remove elements from the stream (as may be the case for 1021 * {@code flatMap} or {@code filter} operations). Thus the count is the 1022 * size of the {@code List} and there is no need to execute the pipeline 1023 * and, as a side-effect, print out the list elements. 1024 * 1025 * @return the count of elements in this stream 1026 */ 1027 long count(); 1028 1029 /** 1030 * Returns whether any elements of this stream match the provided 1031 * predicate. May not evaluate the predicate on all elements if not 1032 * necessary for determining the result. If the stream is empty then 1033 * {@code false} is returned and the predicate is not evaluated. 1034 * 1035 * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting 1036 * terminal operation</a>. 1037 * 1038 * @apiNote 1039 * This method evaluates the <em>existential quantification</em> of the 1040 * predicate over the elements of the stream (for some x P(x)). 1041 * 1042 * @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>, 1043 * <a href="package-summary.html#Statelessness">stateless</a> 1044 * predicate to apply to elements of this stream 1045 * @return {@code true} if any elements of the stream match the provided 1046 * predicate, otherwise {@code false} 1047 */ 1048 boolean anyMatch(Predicate<? super T> predicate); 1049 1050 /** 1051 * Returns whether all elements of this stream match the provided predicate. 1052 * May not evaluate the predicate on all elements if not necessary for 1053 * determining the result. If the stream is empty then {@code true} is 1054 * returned and the predicate is not evaluated. 1055 * 1056 * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting 1057 * terminal operation</a>. 1058 * 1059 * @apiNote 1060 * This method evaluates the <em>universal quantification</em> of the 1061 * predicate over the elements of the stream (for all x P(x)). If the 1062 * stream is empty, the quantification is said to be <em>vacuously 1063 * satisfied</em> and is always {@code true} (regardless of P(x)). 1064 * 1065 * @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>, 1066 * <a href="package-summary.html#Statelessness">stateless</a> 1067 * predicate to apply to elements of this stream 1068 * @return {@code true} if either all elements of the stream match the 1069 * provided predicate or the stream is empty, otherwise {@code false} 1070 */ 1071 boolean allMatch(Predicate<? super T> predicate); 1072 1073 /** 1074 * Returns whether no elements of this stream match the provided predicate. 1075 * May not evaluate the predicate on all elements if not necessary for 1076 * determining the result. If the stream is empty then {@code true} is 1077 * returned and the predicate is not evaluated. 1078 * 1079 * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting 1080 * terminal operation</a>. 1081 * 1082 * @apiNote 1083 * This method evaluates the <em>universal quantification</em> of the 1084 * negated predicate over the elements of the stream (for all x ~P(x)). If 1085 * the stream is empty, the quantification is said to be vacuously satisfied 1086 * and is always {@code true}, regardless of P(x). 1087 * 1088 * @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>, 1089 * <a href="package-summary.html#Statelessness">stateless</a> 1090 * predicate to apply to elements of this stream 1091 * @return {@code true} if either no elements of the stream match the 1092 * provided predicate or the stream is empty, otherwise {@code false} 1093 */ 1094 boolean noneMatch(Predicate<? super T> predicate); 1095 1096 /** 1097 * Returns an {@link Optional} describing the first element of this stream, 1098 * or an empty {@code Optional} if the stream is empty. If the stream has 1099 * no encounter order, then any element may be returned. 1100 * 1101 * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting 1102 * terminal operation</a>. 1103 * 1104 * @return an {@code Optional} describing the first element of this stream, 1105 * or an empty {@code Optional} if the stream is empty 1106 * @throws NullPointerException if the element selected is null 1107 */ 1108 Optional<T> findFirst(); 1109 1110 /** 1111 * Returns an {@link Optional} describing some element of the stream, or an 1112 * empty {@code Optional} if the stream is empty. 1113 * 1114 * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting 1115 * terminal operation</a>. 1116 * 1117 * <p>The behavior of this operation is explicitly nondeterministic; it is 1118 * free to select any element in the stream. This is to allow for maximal 1119 * performance in parallel operations; the cost is that multiple invocations 1120 * on the same source may not return the same result. (If a stable result 1121 * is desired, use {@link #findFirst()} instead.) 1122 * 1123 * @return an {@code Optional} describing some element of this stream, or an 1124 * empty {@code Optional} if the stream is empty 1125 * @throws NullPointerException if the element selected is null 1126 * @see #findFirst() 1127 */ 1128 Optional<T> findAny(); 1129 1130 // Static factories 1131 1132 /** 1133 * Returns a builder for a {@code Stream}. 1134 * 1135 * @param <T> type of elements 1136 * @return a stream builder 1137 */ 1138 public static<T> Builder<T> builder() { 1139 return new Streams.StreamBuilderImpl<>(); 1140 } 1141 1142 /** 1143 * Returns an empty sequential {@code Stream}. 1144 * 1145 * @param <T> the type of stream elements 1146 * @return an empty sequential stream 1147 */ 1148 public static<T> Stream<T> empty() { 1149 return StreamSupport.stream(Spliterators.<T>emptySpliterator(), false); 1150 } 1151 1152 /** 1153 * Returns a sequential {@code Stream} containing a single element. 1154 * 1155 * @param t the single element 1156 * @param <T> the type of stream elements 1157 * @return a singleton sequential stream 1158 */ 1159 public static<T> Stream<T> of(T t) { 1160 return StreamSupport.stream(new Streams.StreamBuilderImpl<>(t), false); 1161 } 1162 1163 /** 1164 * Returns a sequential {@code Stream} containing a single element, if 1165 * non-null, otherwise returns an empty {@code Stream}. 1166 * 1167 * @param t the single element 1168 * @param <T> the type of stream elements 1169 * @return a stream with a single element if the specified element 1170 * is non-null, otherwise an empty stream 1171 * @since 9 1172 */ 1173 public static<T> Stream<T> ofNullable(T t) { 1174 return t == null ? Stream.empty() 1175 : StreamSupport.stream(new Streams.StreamBuilderImpl<>(t), false); 1176 } 1177 1178 /** 1179 * Returns a sequential ordered stream whose elements are the specified values. 1180 * 1181 * @param <T> the type of stream elements 1182 * @param values the elements of the new stream 1183 * @return the new stream 1184 */ 1185 @SafeVarargs 1186 @SuppressWarnings("varargs") // Creating a stream from an array is safe 1187 public static<T> Stream<T> of(T... values) { 1188 return Arrays.stream(values); 1189 } 1190 1191 /** 1192 * Returns an infinite sequential ordered {@code Stream} produced by iterative 1193 * application of a function {@code f} to an initial element {@code seed}, 1194 * producing a {@code Stream} consisting of {@code seed}, {@code f(seed)}, 1195 * {@code f(f(seed))}, etc. 1196 * 1197 * <p>The first element (position {@code 0}) in the {@code Stream} will be 1198 * the provided {@code seed}. For {@code n > 0}, the element at position 1199 * {@code n}, will be the result of applying the function {@code f} to the 1200 * element at position {@code n - 1}. 1201 * 1202 * <p>The action of applying {@code f} for one element 1203 * <a href="../concurrent/package-summary.html#MemoryVisibility"><i>happens-before</i></a> 1204 * the action of applying {@code f} for subsequent elements. For any given 1205 * element the action may be performed in whatever thread the library 1206 * chooses. 1207 * 1208 * @param <T> the type of stream elements 1209 * @param seed the initial element 1210 * @param f a function to be applied to the previous element to produce 1211 * a new element 1212 * @return a new sequential {@code Stream} 1213 */ 1214 public static<T> Stream<T> iterate(final T seed, final UnaryOperator<T> f) { 1215 Objects.requireNonNull(f); 1216 Spliterator<T> spliterator = new Spliterators.AbstractSpliterator<>(Long.MAX_VALUE, 1217 Spliterator.ORDERED | Spliterator.IMMUTABLE) { 1218 T prev; 1219 boolean started; 1220 1221 @Override 1222 public boolean tryAdvance(Consumer<? super T> action) { 1223 Objects.requireNonNull(action); 1224 T t; 1225 if (started) 1226 t = f.apply(prev); 1227 else { 1228 t = seed; 1229 started = true; 1230 } 1231 action.accept(prev = t); 1232 return true; 1233 } 1234 }; 1235 return StreamSupport.stream(spliterator, false); 1236 } 1237 1238 /** 1239 * Returns a sequential ordered {@code Stream} produced by iterative 1240 * application of the given {@code next} function to an initial element, 1241 * conditioned on satisfying the given {@code hasNext} predicate. The 1242 * stream terminates as soon as the {@code hasNext} predicate returns false. 1243 * 1244 * <p>{@code Stream.iterate} should produce the same sequence of elements as 1245 * produced by the corresponding for-loop: 1246 * <pre>{@code 1247 * for (T index=seed; hasNext.test(index); index = next.apply(index)) { 1248 * ... 1249 * } 1250 * }</pre> 1251 * 1252 * <p>The resulting sequence may be empty if the {@code hasNext} predicate 1253 * does not hold on the seed value. Otherwise the first element will be the 1254 * supplied {@code seed} value, the next element (if present) will be the 1255 * result of applying the {@code next} function to the {@code seed} value, 1256 * and so on iteratively until the {@code hasNext} predicate indicates that 1257 * the stream should terminate. 1258 * 1259 * <p>The action of applying the {@code hasNext} predicate to an element 1260 * <a href="../concurrent/package-summary.html#MemoryVisibility"><i>happens-before</i></a> 1261 * the action of applying the {@code next} function to that element. The 1262 * action of applying the {@code next} function for one element 1263 * <i>happens-before</i> the action of applying the {@code hasNext} 1264 * predicate for subsequent elements. For any given element an action may 1265 * be performed in whatever thread the library chooses. 1266 * 1267 * @param <T> the type of stream elements 1268 * @param seed the initial element 1269 * @param hasNext a predicate to apply to elements to determine when the 1270 * stream must terminate. 1271 * @param next a function to be applied to the previous element to produce 1272 * a new element 1273 * @return a new sequential {@code Stream} 1274 * @since 9 1275 */ 1276 public static<T> Stream<T> iterate(T seed, Predicate<? super T> hasNext, UnaryOperator<T> next) { 1277 Objects.requireNonNull(next); 1278 Objects.requireNonNull(hasNext); 1279 Spliterator<T> spliterator = new Spliterators.AbstractSpliterator<>(Long.MAX_VALUE, 1280 Spliterator.ORDERED | Spliterator.IMMUTABLE) { 1281 T prev; 1282 boolean started, finished; 1283 1284 @Override 1285 public boolean tryAdvance(Consumer<? super T> action) { 1286 Objects.requireNonNull(action); 1287 if (finished) 1288 return false; 1289 T t; 1290 if (started) 1291 t = next.apply(prev); 1292 else { 1293 t = seed; 1294 started = true; 1295 } 1296 if (!hasNext.test(t)) { 1297 prev = null; 1298 finished = true; 1299 return false; 1300 } 1301 action.accept(prev = t); 1302 return true; 1303 } 1304 1305 @Override 1306 public void forEachRemaining(Consumer<? super T> action) { 1307 Objects.requireNonNull(action); 1308 if (finished) 1309 return; 1310 finished = true; 1311 T t = started ? next.apply(prev) : seed; 1312 prev = null; 1313 while (hasNext.test(t)) { 1314 action.accept(t); 1315 t = next.apply(t); 1316 } 1317 } 1318 }; 1319 return StreamSupport.stream(spliterator, false); 1320 } 1321 1322 /** 1323 * Returns an infinite sequential unordered stream where each element is 1324 * generated by the provided {@code Supplier}. This is suitable for 1325 * generating constant streams, streams of random elements, etc. 1326 * 1327 * @param <T> the type of stream elements 1328 * @param s the {@code Supplier} of generated elements 1329 * @return a new infinite sequential unordered {@code Stream} 1330 */ 1331 public static<T> Stream<T> generate(Supplier<? extends T> s) { 1332 Objects.requireNonNull(s); 1333 return StreamSupport.stream( 1334 new StreamSpliterators.InfiniteSupplyingSpliterator.OfRef<>(Long.MAX_VALUE, s), false); 1335 } 1336 1337 /** 1338 * Creates a lazily concatenated stream whose elements are all the 1339 * elements of the first stream followed by all the elements of the 1340 * second stream. The resulting stream is ordered if both 1341 * of the input streams are ordered, and parallel if either of the input 1342 * streams is parallel. When the resulting stream is closed, the close 1343 * handlers for both input streams are invoked. 1344 * 1345 * <p>This method operates on the two input streams and binds each stream 1346 * to its source. As a result subsequent modifications to an input stream 1347 * source may not be reflected in the concatenated stream result. 1348 * 1349 * @implNote 1350 * Use caution when constructing streams from repeated concatenation. 1351 * Accessing an element of a deeply concatenated stream can result in deep 1352 * call chains, or even {@code StackOverflowError}. 1353 * 1354 * <p>Subsequent changes to the sequential/parallel execution mode of the 1355 * returned stream are not guaranteed to be propagated to the input streams. 1356 * 1357 * @apiNote 1358 * To preserve optimization opportunities this method binds each stream to 1359 * its source and accepts only two streams as parameters. For example, the 1360 * exact size of the concatenated stream source can be computed if the exact 1361 * size of each input stream source is known. 1362 * To concatenate more streams without binding, or without nested calls to 1363 * this method, try creating a stream of streams and flat-mapping with the 1364 * identity function, for example: 1365 * <pre>{@code 1366 * Stream<T> concat = Stream.of(s1, s2, s3, s4).flatMap(s -> s); 1367 * }</pre> 1368 * 1369 * @param <T> The type of stream elements 1370 * @param a the first stream 1371 * @param b the second stream 1372 * @return the concatenation of the two input streams 1373 */ 1374 public static <T> Stream<T> concat(Stream<? extends T> a, Stream<? extends T> b) { 1375 Objects.requireNonNull(a); 1376 Objects.requireNonNull(b); 1377 1378 @SuppressWarnings("unchecked") 1379 Spliterator<T> split = new Streams.ConcatSpliterator.OfRef<>( 1380 (Spliterator<T>) a.spliterator(), (Spliterator<T>) b.spliterator()); 1381 Stream<T> stream = StreamSupport.stream(split, a.isParallel() || b.isParallel()); 1382 return stream.onClose(Streams.composedClose(a, b)); 1383 } 1384 1385 /** 1386 * A mutable builder for a {@code Stream}. This allows the creation of a 1387 * {@code Stream} by generating elements individually and adding them to the 1388 * {@code Builder} (without the copying overhead that comes from using 1389 * an {@code ArrayList} as a temporary buffer.) 1390 * 1391 * <p>A stream builder has a lifecycle, which starts in a building 1392 * phase, during which elements can be added, and then transitions to a built 1393 * phase, after which elements may not be added. The built phase begins 1394 * when the {@link #build()} method is called, which creates an ordered 1395 * {@code Stream} whose elements are the elements that were added to the stream 1396 * builder, in the order they were added. 1397 * 1398 * @param <T> the type of stream elements 1399 * @see Stream#builder() 1400 * @since 1.8 1401 */ 1402 public interface Builder<T> extends Consumer<T> { 1403 1404 /** 1405 * Adds an element to the stream being built. 1406 * 1407 * @throws IllegalStateException if the builder has already transitioned to 1408 * the built state 1409 */ 1410 @Override 1411 void accept(T t); 1412 1413 /** 1414 * Adds an element to the stream being built. 1415 * 1416 * @implSpec 1417 * The default implementation behaves as if: 1418 * <pre>{@code 1419 * accept(t) 1420 * return this; 1421 * }</pre> 1422 * 1423 * @param t the element to add 1424 * @return {@code this} builder 1425 * @throws IllegalStateException if the builder has already transitioned to 1426 * the built state 1427 */ 1428 default Builder<T> add(T t) { 1429 accept(t); 1430 return this; 1431 } 1432 1433 /** 1434 * Builds the stream, transitioning this builder to the built state. 1435 * An {@code IllegalStateException} is thrown if there are further attempts 1436 * to operate on the builder after it has entered the built state. 1437 * 1438 * @return the built stream 1439 * @throws IllegalStateException if the builder has already transitioned to 1440 * the built state 1441 */ 1442 Stream<T> build(); 1443 1444 } 1445 }