Stream.java revision 14564:d9f0d05b7b32
1/* 2 * Copyright (c) 2012, 2016, 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 */ 25package java.util.stream; 26 27import java.nio.file.Files; 28import java.nio.file.Path; 29import java.util.Arrays; 30import java.util.Collection; 31import java.util.Comparator; 32import java.util.Objects; 33import java.util.Optional; 34import java.util.Spliterator; 35import java.util.Spliterators; 36import java.util.concurrent.ConcurrentHashMap; 37import java.util.function.BiConsumer; 38import java.util.function.BiFunction; 39import java.util.function.BinaryOperator; 40import java.util.function.Consumer; 41import java.util.function.Function; 42import java.util.function.IntFunction; 43import java.util.function.Predicate; 44import java.util.function.Supplier; 45import java.util.function.ToDoubleFunction; 46import java.util.function.ToIntFunction; 47import java.util.function.ToLongFunction; 48import 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 */ 167public 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 containing the elements of this stream 675 */ 676 Object[] toArray(); 677 678 /** 679 * Returns an array containing the elements of this stream, using the 680 * provided {@code generator} function to allocate the returned array, as 681 * well as any additional arrays that might be required for a partitioned 682 * execution or for resizing. 683 * 684 * <p>This is a <a href="package-summary.html#StreamOps">terminal 685 * operation</a>. 686 * 687 * @apiNote 688 * The generator function takes an integer, which is the size of the 689 * desired array, and produces an array of the desired size. This can be 690 * concisely expressed with an array constructor reference: 691 * <pre>{@code 692 * Person[] men = people.stream() 693 * .filter(p -> p.getGender() == MALE) 694 * .toArray(Person[]::new); 695 * }</pre> 696 * 697 * @param <A> the element type of the resulting array 698 * @param generator a function which produces a new array of the desired 699 * type and the provided length 700 * @return an array containing the elements in this stream 701 * @throws ArrayStoreException if the runtime type of the array returned 702 * from the array generator is not a supertype of the runtime type of every 703 * element in this stream 704 */ 705 <A> A[] toArray(IntFunction<A[]> generator); 706 707 /** 708 * Performs a <a href="package-summary.html#Reduction">reduction</a> on the 709 * elements of this stream, using the provided identity value and an 710 * <a href="package-summary.html#Associativity">associative</a> 711 * accumulation function, and returns the reduced value. This is equivalent 712 * to: 713 * <pre>{@code 714 * T result = identity; 715 * for (T element : this stream) 716 * result = accumulator.apply(result, element) 717 * return result; 718 * }</pre> 719 * 720 * but is not constrained to execute sequentially. 721 * 722 * <p>The {@code identity} value must be an identity for the accumulator 723 * function. This means that for all {@code t}, 724 * {@code accumulator.apply(identity, t)} is equal to {@code t}. 725 * The {@code accumulator} function must be an 726 * <a href="package-summary.html#Associativity">associative</a> function. 727 * 728 * <p>This is a <a href="package-summary.html#StreamOps">terminal 729 * operation</a>. 730 * 731 * @apiNote Sum, min, max, average, and string concatenation are all special 732 * cases of reduction. Summing a stream of numbers can be expressed as: 733 * 734 * <pre>{@code 735 * Integer sum = integers.reduce(0, (a, b) -> a+b); 736 * }</pre> 737 * 738 * or: 739 * 740 * <pre>{@code 741 * Integer sum = integers.reduce(0, Integer::sum); 742 * }</pre> 743 * 744 * <p>While this may seem a more roundabout way to perform an aggregation 745 * compared to simply mutating a running total in a loop, reduction 746 * operations parallelize more gracefully, without needing additional 747 * synchronization and with greatly reduced risk of data races. 748 * 749 * @param identity the identity value for the accumulating function 750 * @param accumulator an <a href="package-summary.html#Associativity">associative</a>, 751 * <a href="package-summary.html#NonInterference">non-interfering</a>, 752 * <a href="package-summary.html#Statelessness">stateless</a> 753 * function for combining two values 754 * @return the result of the reduction 755 */ 756 T reduce(T identity, BinaryOperator<T> accumulator); 757 758 /** 759 * Performs a <a href="package-summary.html#Reduction">reduction</a> on the 760 * elements of this stream, using an 761 * <a href="package-summary.html#Associativity">associative</a> accumulation 762 * function, and returns an {@code Optional} describing the reduced value, 763 * if any. This is equivalent to: 764 * <pre>{@code 765 * boolean foundAny = false; 766 * T result = null; 767 * for (T element : this stream) { 768 * if (!foundAny) { 769 * foundAny = true; 770 * result = element; 771 * } 772 * else 773 * result = accumulator.apply(result, element); 774 * } 775 * return foundAny ? Optional.of(result) : Optional.empty(); 776 * }</pre> 777 * 778 * but is not constrained to execute sequentially. 779 * 780 * <p>The {@code accumulator} function must be an 781 * <a href="package-summary.html#Associativity">associative</a> function. 782 * 783 * <p>This is a <a href="package-summary.html#StreamOps">terminal 784 * operation</a>. 785 * 786 * @param accumulator an <a href="package-summary.html#Associativity">associative</a>, 787 * <a href="package-summary.html#NonInterference">non-interfering</a>, 788 * <a href="package-summary.html#Statelessness">stateless</a> 789 * function for combining two values 790 * @return an {@link Optional} describing the result of the reduction 791 * @throws NullPointerException if the result of the reduction is null 792 * @see #reduce(Object, BinaryOperator) 793 * @see #min(Comparator) 794 * @see #max(Comparator) 795 */ 796 Optional<T> reduce(BinaryOperator<T> accumulator); 797 798 /** 799 * Performs a <a href="package-summary.html#Reduction">reduction</a> on the 800 * elements of this stream, using the provided identity, accumulation and 801 * combining functions. This is equivalent to: 802 * <pre>{@code 803 * U result = identity; 804 * for (T element : this stream) 805 * result = accumulator.apply(result, element) 806 * return result; 807 * }</pre> 808 * 809 * but is not constrained to execute sequentially. 810 * 811 * <p>The {@code identity} value must be an identity for the combiner 812 * function. This means that for all {@code u}, {@code combiner(identity, u)} 813 * is equal to {@code u}. Additionally, the {@code combiner} function 814 * must be compatible with the {@code accumulator} function; for all 815 * {@code u} and {@code t}, the following must hold: 816 * <pre>{@code 817 * combiner.apply(u, accumulator.apply(identity, t)) == accumulator.apply(u, t) 818 * }</pre> 819 * 820 * <p>This is a <a href="package-summary.html#StreamOps">terminal 821 * operation</a>. 822 * 823 * @apiNote Many reductions using this form can be represented more simply 824 * by an explicit combination of {@code map} and {@code reduce} operations. 825 * The {@code accumulator} function acts as a fused mapper and accumulator, 826 * which can sometimes be more efficient than separate mapping and reduction, 827 * such as when knowing the previously reduced value allows you to avoid 828 * some computation. 829 * 830 * @param <U> The type of the result 831 * @param identity the identity value for the combiner function 832 * @param accumulator an <a href="package-summary.html#Associativity">associative</a>, 833 * <a href="package-summary.html#NonInterference">non-interfering</a>, 834 * <a href="package-summary.html#Statelessness">stateless</a> 835 * function for incorporating an additional element into a result 836 * @param combiner an <a href="package-summary.html#Associativity">associative</a>, 837 * <a href="package-summary.html#NonInterference">non-interfering</a>, 838 * <a href="package-summary.html#Statelessness">stateless</a> 839 * function for combining two values, which must be 840 * compatible with the accumulator function 841 * @return the result of the reduction 842 * @see #reduce(BinaryOperator) 843 * @see #reduce(Object, BinaryOperator) 844 */ 845 <U> U reduce(U identity, 846 BiFunction<U, ? super T, U> accumulator, 847 BinaryOperator<U> combiner); 848 849 /** 850 * Performs a <a href="package-summary.html#MutableReduction">mutable 851 * reduction</a> operation on the elements of this stream. A mutable 852 * reduction is one in which the reduced value is a mutable result container, 853 * such as an {@code ArrayList}, and elements are incorporated by updating 854 * the state of the result rather than by replacing the result. This 855 * produces a result equivalent to: 856 * <pre>{@code 857 * R result = supplier.get(); 858 * for (T element : this stream) 859 * accumulator.accept(result, element); 860 * return result; 861 * }</pre> 862 * 863 * <p>Like {@link #reduce(Object, BinaryOperator)}, {@code collect} operations 864 * can be parallelized without requiring additional synchronization. 865 * 866 * <p>This is a <a href="package-summary.html#StreamOps">terminal 867 * operation</a>. 868 * 869 * @apiNote There are many existing classes in the JDK whose signatures are 870 * well-suited for use with method references as arguments to {@code collect()}. 871 * For example, the following will accumulate strings into an {@code ArrayList}: 872 * <pre>{@code 873 * List<String> asList = stringStream.collect(ArrayList::new, ArrayList::add, 874 * ArrayList::addAll); 875 * }</pre> 876 * 877 * <p>The following will take a stream of strings and concatenates them into a 878 * single string: 879 * <pre>{@code 880 * String concat = stringStream.collect(StringBuilder::new, StringBuilder::append, 881 * StringBuilder::append) 882 * .toString(); 883 * }</pre> 884 * 885 * @param <R> type of the result 886 * @param supplier a function that creates a new result container. For a 887 * parallel execution, this function may be called 888 * multiple times and must return a fresh value each time. 889 * @param accumulator an <a href="package-summary.html#Associativity">associative</a>, 890 * <a href="package-summary.html#NonInterference">non-interfering</a>, 891 * <a href="package-summary.html#Statelessness">stateless</a> 892 * function for incorporating an additional element into a result 893 * @param combiner an <a href="package-summary.html#Associativity">associative</a>, 894 * <a href="package-summary.html#NonInterference">non-interfering</a>, 895 * <a href="package-summary.html#Statelessness">stateless</a> 896 * function for combining two values, which must be 897 * compatible with the accumulator function 898 * @return the result of the reduction 899 */ 900 <R> R collect(Supplier<R> supplier, 901 BiConsumer<R, ? super T> accumulator, 902 BiConsumer<R, R> combiner); 903 904 /** 905 * Performs a <a href="package-summary.html#MutableReduction">mutable 906 * reduction</a> operation on the elements of this stream using a 907 * {@code Collector}. A {@code Collector} 908 * encapsulates the functions used as arguments to 909 * {@link #collect(Supplier, BiConsumer, BiConsumer)}, allowing for reuse of 910 * collection strategies and composition of collect operations such as 911 * multiple-level grouping or partitioning. 912 * 913 * <p>If the stream is parallel, and the {@code Collector} 914 * is {@link Collector.Characteristics#CONCURRENT concurrent}, and 915 * either the stream is unordered or the collector is 916 * {@link Collector.Characteristics#UNORDERED unordered}, 917 * then a concurrent reduction will be performed (see {@link Collector} for 918 * details on concurrent reduction.) 919 * 920 * <p>This is a <a href="package-summary.html#StreamOps">terminal 921 * operation</a>. 922 * 923 * <p>When executed in parallel, multiple intermediate results may be 924 * instantiated, populated, and merged so as to maintain isolation of 925 * mutable data structures. Therefore, even when executed in parallel 926 * with non-thread-safe data structures (such as {@code ArrayList}), no 927 * additional synchronization is needed for a parallel reduction. 928 * 929 * @apiNote 930 * The following will accumulate strings into an ArrayList: 931 * <pre>{@code 932 * List<String> asList = stringStream.collect(Collectors.toList()); 933 * }</pre> 934 * 935 * <p>The following will classify {@code Person} objects by city: 936 * <pre>{@code 937 * Map<String, List<Person>> peopleByCity 938 * = personStream.collect(Collectors.groupingBy(Person::getCity)); 939 * }</pre> 940 * 941 * <p>The following will classify {@code Person} objects by state and city, 942 * cascading two {@code Collector}s together: 943 * <pre>{@code 944 * Map<String, Map<String, List<Person>>> peopleByStateAndCity 945 * = personStream.collect(Collectors.groupingBy(Person::getState, 946 * Collectors.groupingBy(Person::getCity))); 947 * }</pre> 948 * 949 * @param <R> the type of the result 950 * @param <A> the intermediate accumulation type of the {@code Collector} 951 * @param collector the {@code Collector} describing the reduction 952 * @return the result of the reduction 953 * @see #collect(Supplier, BiConsumer, BiConsumer) 954 * @see Collectors 955 */ 956 <R, A> R collect(Collector<? super T, A, R> collector); 957 958 /** 959 * Returns the minimum element of this stream according to the provided 960 * {@code Comparator}. This is a special case of a 961 * <a href="package-summary.html#Reduction">reduction</a>. 962 * 963 * <p>This is a <a href="package-summary.html#StreamOps">terminal operation</a>. 964 * 965 * @param comparator a <a href="package-summary.html#NonInterference">non-interfering</a>, 966 * <a href="package-summary.html#Statelessness">stateless</a> 967 * {@code Comparator} to compare elements of this stream 968 * @return an {@code Optional} describing the minimum element of this stream, 969 * or an empty {@code Optional} if the stream is empty 970 * @throws NullPointerException if the minimum element is null 971 */ 972 Optional<T> min(Comparator<? super T> comparator); 973 974 /** 975 * Returns the maximum element of this stream according to the provided 976 * {@code Comparator}. This is a special case of a 977 * <a href="package-summary.html#Reduction">reduction</a>. 978 * 979 * <p>This is a <a href="package-summary.html#StreamOps">terminal 980 * operation</a>. 981 * 982 * @param comparator a <a href="package-summary.html#NonInterference">non-interfering</a>, 983 * <a href="package-summary.html#Statelessness">stateless</a> 984 * {@code Comparator} to compare elements of this stream 985 * @return an {@code Optional} describing the maximum element of this stream, 986 * or an empty {@code Optional} if the stream is empty 987 * @throws NullPointerException if the maximum element is null 988 */ 989 Optional<T> max(Comparator<? super T> comparator); 990 991 /** 992 * Returns the count of elements in this stream. This is a special case of 993 * a <a href="package-summary.html#Reduction">reduction</a> and is 994 * equivalent to: 995 * <pre>{@code 996 * return mapToLong(e -> 1L).sum(); 997 * }</pre> 998 * 999 * <p>This is a <a href="package-summary.html#StreamOps">terminal operation</a>. 1000 * 1001 * @apiNote 1002 * An implementation may choose to not execute the stream pipeline (either 1003 * sequentially or in parallel) if it is capable of computing the count 1004 * directly from the stream source. In such cases no source elements will 1005 * be traversed and no intermediate operations will be evaluated. 1006 * Behavioral parameters with side-effects, which are strongly discouraged 1007 * except for harmless cases such as debugging, may be affected. For 1008 * example, consider the following stream: 1009 * <pre>{@code 1010 * List<String> l = Arrays.asList("A", "B", "C", "D"); 1011 * long count = l.stream().peek(System.out::println).count(); 1012 * }</pre> 1013 * The number of elements covered by the stream source, a {@code List}, is 1014 * known and the intermediate operation, {@code peek}, does not inject into 1015 * or remove elements from the stream (as may be the case for 1016 * {@code flatMap} or {@code filter} operations). Thus the count is the 1017 * size of the {@code List} and there is no need to execute the pipeline 1018 * and, as a side-effect, print out the list elements. 1019 * 1020 * @return the count of elements in this stream 1021 */ 1022 long count(); 1023 1024 /** 1025 * Returns whether any elements of this stream match the provided 1026 * predicate. May not evaluate the predicate on all elements if not 1027 * necessary for determining the result. If the stream is empty then 1028 * {@code false} is returned and the predicate is not evaluated. 1029 * 1030 * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting 1031 * terminal operation</a>. 1032 * 1033 * @apiNote 1034 * This method evaluates the <em>existential quantification</em> of the 1035 * predicate over the elements of the stream (for some x P(x)). 1036 * 1037 * @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>, 1038 * <a href="package-summary.html#Statelessness">stateless</a> 1039 * predicate to apply to elements of this stream 1040 * @return {@code true} if any elements of the stream match the provided 1041 * predicate, otherwise {@code false} 1042 */ 1043 boolean anyMatch(Predicate<? super T> predicate); 1044 1045 /** 1046 * Returns whether all elements of this stream match the provided predicate. 1047 * May not evaluate the predicate on all elements if not necessary for 1048 * determining the result. If the stream is empty then {@code true} is 1049 * returned and the predicate is not evaluated. 1050 * 1051 * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting 1052 * terminal operation</a>. 1053 * 1054 * @apiNote 1055 * This method evaluates the <em>universal quantification</em> of the 1056 * predicate over the elements of the stream (for all x P(x)). If the 1057 * stream is empty, the quantification is said to be <em>vacuously 1058 * satisfied</em> and is always {@code true} (regardless of P(x)). 1059 * 1060 * @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>, 1061 * <a href="package-summary.html#Statelessness">stateless</a> 1062 * predicate to apply to elements of this stream 1063 * @return {@code true} if either all elements of the stream match the 1064 * provided predicate or the stream is empty, otherwise {@code false} 1065 */ 1066 boolean allMatch(Predicate<? super T> predicate); 1067 1068 /** 1069 * Returns whether no elements of this stream match the provided predicate. 1070 * May not evaluate the predicate on all elements if not necessary for 1071 * determining the result. If the stream is empty then {@code true} is 1072 * returned and the predicate is not evaluated. 1073 * 1074 * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting 1075 * terminal operation</a>. 1076 * 1077 * @apiNote 1078 * This method evaluates the <em>universal quantification</em> of the 1079 * negated predicate over the elements of the stream (for all x ~P(x)). If 1080 * the stream is empty, the quantification is said to be vacuously satisfied 1081 * and is always {@code true}, regardless of P(x). 1082 * 1083 * @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>, 1084 * <a href="package-summary.html#Statelessness">stateless</a> 1085 * predicate to apply to elements of this stream 1086 * @return {@code true} if either no elements of the stream match the 1087 * provided predicate or the stream is empty, otherwise {@code false} 1088 */ 1089 boolean noneMatch(Predicate<? super T> predicate); 1090 1091 /** 1092 * Returns an {@link Optional} describing the first element of this stream, 1093 * or an empty {@code Optional} if the stream is empty. If the stream has 1094 * no encounter order, then any element may be returned. 1095 * 1096 * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting 1097 * terminal operation</a>. 1098 * 1099 * @return an {@code Optional} describing the first element of this stream, 1100 * or an empty {@code Optional} if the stream is empty 1101 * @throws NullPointerException if the element selected is null 1102 */ 1103 Optional<T> findFirst(); 1104 1105 /** 1106 * Returns an {@link Optional} describing some element of the stream, or an 1107 * empty {@code Optional} if the stream is empty. 1108 * 1109 * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting 1110 * terminal operation</a>. 1111 * 1112 * <p>The behavior of this operation is explicitly nondeterministic; it is 1113 * free to select any element in the stream. This is to allow for maximal 1114 * performance in parallel operations; the cost is that multiple invocations 1115 * on the same source may not return the same result. (If a stable result 1116 * is desired, use {@link #findFirst()} instead.) 1117 * 1118 * @return an {@code Optional} describing some element of this stream, or an 1119 * empty {@code Optional} if the stream is empty 1120 * @throws NullPointerException if the element selected is null 1121 * @see #findFirst() 1122 */ 1123 Optional<T> findAny(); 1124 1125 // Static factories 1126 1127 /** 1128 * Returns a builder for a {@code Stream}. 1129 * 1130 * @param <T> type of elements 1131 * @return a stream builder 1132 */ 1133 public static<T> Builder<T> builder() { 1134 return new Streams.StreamBuilderImpl<>(); 1135 } 1136 1137 /** 1138 * Returns an empty sequential {@code Stream}. 1139 * 1140 * @param <T> the type of stream elements 1141 * @return an empty sequential stream 1142 */ 1143 public static<T> Stream<T> empty() { 1144 return StreamSupport.stream(Spliterators.<T>emptySpliterator(), false); 1145 } 1146 1147 /** 1148 * Returns a sequential {@code Stream} containing a single element. 1149 * 1150 * @param t the single element 1151 * @param <T> the type of stream elements 1152 * @return a singleton sequential stream 1153 */ 1154 public static<T> Stream<T> of(T t) { 1155 return StreamSupport.stream(new Streams.StreamBuilderImpl<>(t), false); 1156 } 1157 1158 /** 1159 * Returns a sequential {@code Stream} containing a single element, if 1160 * non-null, otherwise returns an empty {@code Stream}. 1161 * 1162 * @param t the single element 1163 * @param <T> the type of stream elements 1164 * @return a stream with a single element if the specified element 1165 * is non-null, otherwise an empty stream 1166 * @since 9 1167 */ 1168 public static<T> Stream<T> ofNullable(T t) { 1169 return t == null ? Stream.empty() 1170 : StreamSupport.stream(new Streams.StreamBuilderImpl<>(t), false); 1171 } 1172 1173 /** 1174 * Returns a sequential ordered stream whose elements are the specified values. 1175 * 1176 * @param <T> the type of stream elements 1177 * @param values the elements of the new stream 1178 * @return the new stream 1179 */ 1180 @SafeVarargs 1181 @SuppressWarnings("varargs") // Creating a stream from an array is safe 1182 public static<T> Stream<T> of(T... values) { 1183 return Arrays.stream(values); 1184 } 1185 1186 /** 1187 * Returns an infinite sequential ordered {@code Stream} produced by iterative 1188 * application of a function {@code f} to an initial element {@code seed}, 1189 * producing a {@code Stream} consisting of {@code seed}, {@code f(seed)}, 1190 * {@code f(f(seed))}, etc. 1191 * 1192 * <p>The first element (position {@code 0}) in the {@code Stream} will be 1193 * the provided {@code seed}. For {@code n > 0}, the element at position 1194 * {@code n}, will be the result of applying the function {@code f} to the 1195 * element at position {@code n - 1}. 1196 * 1197 * @param <T> the type of stream elements 1198 * @param seed the initial element 1199 * @param f a function to be applied to the previous element to produce 1200 * a new element 1201 * @return a new sequential {@code Stream} 1202 */ 1203 public static<T> Stream<T> iterate(final T seed, final UnaryOperator<T> f) { 1204 Objects.requireNonNull(f); 1205 Spliterator<T> spliterator = new Spliterators.AbstractSpliterator<>(Long.MAX_VALUE, 1206 Spliterator.ORDERED | Spliterator.IMMUTABLE) { 1207 T prev; 1208 boolean started; 1209 1210 @Override 1211 public boolean tryAdvance(Consumer<? super T> action) { 1212 Objects.requireNonNull(action); 1213 T t; 1214 if (started) 1215 t = f.apply(prev); 1216 else { 1217 t = seed; 1218 started = true; 1219 } 1220 action.accept(prev = t); 1221 return true; 1222 } 1223 }; 1224 return StreamSupport.stream(spliterator, false); 1225 } 1226 1227 /** 1228 * Returns a sequential ordered {@code Stream} produced by iterative 1229 * application of a function to an initial element, conditioned on 1230 * satisfying the supplied predicate. The stream terminates as soon as 1231 * the predicate returns false. 1232 * 1233 * <p> 1234 * {@code Stream.iterate} should produce the same sequence of elements as 1235 * produced by the corresponding for-loop: 1236 * <pre>{@code 1237 * for (T index=seed; predicate.test(index); index = f.apply(index)) { 1238 * ... 1239 * } 1240 * }</pre> 1241 * 1242 * <p> 1243 * The resulting sequence may be empty if the predicate does not hold on 1244 * the seed value. Otherwise the first element will be the supplied seed 1245 * value, the next element (if present) will be the result of applying the 1246 * function f to the seed value, and so on iteratively until the predicate 1247 * indicates that the stream should terminate. 1248 * 1249 * @param <T> the type of stream elements 1250 * @param seed the initial element 1251 * @param predicate a predicate to apply to elements to determine when the 1252 * stream must terminate. 1253 * @param f a function to be applied to the previous element to produce 1254 * a new element 1255 * @return a new sequential {@code Stream} 1256 * @since 9 1257 */ 1258 public static<T> Stream<T> iterate(T seed, Predicate<? super T> predicate, UnaryOperator<T> f) { 1259 Objects.requireNonNull(f); 1260 Objects.requireNonNull(predicate); 1261 Spliterator<T> spliterator = new Spliterators.AbstractSpliterator<>(Long.MAX_VALUE, 1262 Spliterator.ORDERED | Spliterator.IMMUTABLE) { 1263 T prev; 1264 boolean started, finished; 1265 1266 @Override 1267 public boolean tryAdvance(Consumer<? super T> action) { 1268 Objects.requireNonNull(action); 1269 if (finished) 1270 return false; 1271 T t; 1272 if (started) 1273 t = f.apply(prev); 1274 else { 1275 t = seed; 1276 started = true; 1277 } 1278 if (!predicate.test(t)) { 1279 prev = null; 1280 finished = true; 1281 return false; 1282 } 1283 action.accept(prev = t); 1284 return true; 1285 } 1286 1287 @Override 1288 public void forEachRemaining(Consumer<? super T> action) { 1289 Objects.requireNonNull(action); 1290 if (finished) 1291 return; 1292 finished = true; 1293 T t = started ? f.apply(prev) : seed; 1294 prev = null; 1295 while (predicate.test(t)) { 1296 action.accept(t); 1297 t = f.apply(t); 1298 } 1299 } 1300 }; 1301 return StreamSupport.stream(spliterator, false); 1302 } 1303 1304 /** 1305 * Returns an infinite sequential unordered stream where each element is 1306 * generated by the provided {@code Supplier}. This is suitable for 1307 * generating constant streams, streams of random elements, etc. 1308 * 1309 * @param <T> the type of stream elements 1310 * @param s the {@code Supplier} of generated elements 1311 * @return a new infinite sequential unordered {@code Stream} 1312 */ 1313 public static<T> Stream<T> generate(Supplier<T> s) { 1314 Objects.requireNonNull(s); 1315 return StreamSupport.stream( 1316 new StreamSpliterators.InfiniteSupplyingSpliterator.OfRef<>(Long.MAX_VALUE, s), false); 1317 } 1318 1319 /** 1320 * Creates a lazily concatenated stream whose elements are all the 1321 * elements of the first stream followed by all the elements of the 1322 * second stream. The resulting stream is ordered if both 1323 * of the input streams are ordered, and parallel if either of the input 1324 * streams is parallel. When the resulting stream is closed, the close 1325 * handlers for both input streams are invoked. 1326 * 1327 * @implNote 1328 * Use caution when constructing streams from repeated concatenation. 1329 * Accessing an element of a deeply concatenated stream can result in deep 1330 * call chains, or even {@code StackOverflowError}. 1331 * 1332 * <p>Subsequent changes to the sequential/parallel execution mode of the 1333 * returned stream are not guaranteed to be propagated to the input streams. 1334 * 1335 * @param <T> The type of stream elements 1336 * @param a the first stream 1337 * @param b the second stream 1338 * @return the concatenation of the two input streams 1339 */ 1340 public static <T> Stream<T> concat(Stream<? extends T> a, Stream<? extends T> b) { 1341 Objects.requireNonNull(a); 1342 Objects.requireNonNull(b); 1343 1344 @SuppressWarnings("unchecked") 1345 Spliterator<T> split = new Streams.ConcatSpliterator.OfRef<>( 1346 (Spliterator<T>) a.spliterator(), (Spliterator<T>) b.spliterator()); 1347 Stream<T> stream = StreamSupport.stream(split, a.isParallel() || b.isParallel()); 1348 return stream.onClose(Streams.composedClose(a, b)); 1349 } 1350 1351 /** 1352 * A mutable builder for a {@code Stream}. This allows the creation of a 1353 * {@code Stream} by generating elements individually and adding them to the 1354 * {@code Builder} (without the copying overhead that comes from using 1355 * an {@code ArrayList} as a temporary buffer.) 1356 * 1357 * <p>A stream builder has a lifecycle, which starts in a building 1358 * phase, during which elements can be added, and then transitions to a built 1359 * phase, after which elements may not be added. The built phase begins 1360 * when the {@link #build()} method is called, which creates an ordered 1361 * {@code Stream} whose elements are the elements that were added to the stream 1362 * builder, in the order they were added. 1363 * 1364 * @param <T> the type of stream elements 1365 * @see Stream#builder() 1366 * @since 1.8 1367 */ 1368 public interface Builder<T> extends Consumer<T> { 1369 1370 /** 1371 * Adds an element to the stream being built. 1372 * 1373 * @throws IllegalStateException if the builder has already transitioned to 1374 * the built state 1375 */ 1376 @Override 1377 void accept(T t); 1378 1379 /** 1380 * Adds an element to the stream being built. 1381 * 1382 * @implSpec 1383 * The default implementation behaves as if: 1384 * <pre>{@code 1385 * accept(t) 1386 * return this; 1387 * }</pre> 1388 * 1389 * @param t the element to add 1390 * @return {@code this} builder 1391 * @throws IllegalStateException if the builder has already transitioned to 1392 * the built state 1393 */ 1394 default Builder<T> add(T t) { 1395 accept(t); 1396 return this; 1397 } 1398 1399 /** 1400 * Builds the stream, transitioning this builder to the built state. 1401 * An {@code IllegalStateException} is thrown if there are further attempts 1402 * to operate on the builder after it has entered the built state. 1403 * 1404 * @return the built stream 1405 * @throws IllegalStateException if the builder has already transitioned to 1406 * the built state 1407 */ 1408 Stream<T> build(); 1409 1410 } 1411} 1412