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 */ 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 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> the type of the mutable result container 886 * @param supplier a function that creates a new mutable result container. 887 * For a 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 that must fold an element into a result 893 * container. 894 * @param combiner an <a href="package-summary.html#Associativity">associative</a>, 895 * <a href="package-summary.html#NonInterference">non-interfering</a>, 896 * <a href="package-summary.html#Statelessness">stateless</a> 897 * function that accepts two partial result containers 898 * and merges them, which must be compatible with the 899 * accumulator function. The combiner function must fold 900 * the elements from the second result container into the 901 * first result container. 902 * @return the result of the reduction 903 */ 904 <R> R collect(Supplier<R> supplier, 905 BiConsumer<R, ? super T> accumulator, 906 BiConsumer<R, R> combiner); 907 908 /** 909 * Performs a <a href="package-summary.html#MutableReduction">mutable 910 * reduction</a> operation on the elements of this stream using a 911 * {@code Collector}. A {@code Collector} 912 * encapsulates the functions used as arguments to 913 * {@link #collect(Supplier, BiConsumer, BiConsumer)}, allowing for reuse of 914 * collection strategies and composition of collect operations such as 915 * multiple-level grouping or partitioning. 916 * 917 * <p>If the stream is parallel, and the {@code Collector} 918 * is {@link Collector.Characteristics#CONCURRENT concurrent}, and 919 * either the stream is unordered or the collector is 920 * {@link Collector.Characteristics#UNORDERED unordered}, 921 * then a concurrent reduction will be performed (see {@link Collector} for 922 * details on concurrent reduction.) 923 * 924 * <p>This is a <a href="package-summary.html#StreamOps">terminal 925 * operation</a>. 926 * 927 * <p>When executed in parallel, multiple intermediate results may be 928 * instantiated, populated, and merged so as to maintain isolation of 929 * mutable data structures. Therefore, even when executed in parallel 930 * with non-thread-safe data structures (such as {@code ArrayList}), no 931 * additional synchronization is needed for a parallel reduction. 932 * 933 * @apiNote 934 * The following will accumulate strings into an ArrayList: 935 * <pre>{@code 936 * List<String> asList = stringStream.collect(Collectors.toList()); 937 * }</pre> 938 * 939 * <p>The following will classify {@code Person} objects by city: 940 * <pre>{@code 941 * Map<String, List<Person>> peopleByCity 942 * = personStream.collect(Collectors.groupingBy(Person::getCity)); 943 * }</pre> 944 * 945 * <p>The following will classify {@code Person} objects by state and city, 946 * cascading two {@code Collector}s together: 947 * <pre>{@code 948 * Map<String, Map<String, List<Person>>> peopleByStateAndCity 949 * = personStream.collect(Collectors.groupingBy(Person::getState, 950 * Collectors.groupingBy(Person::getCity))); 951 * }</pre> 952 * 953 * @param <R> the type of the result 954 * @param <A> the intermediate accumulation type of the {@code Collector} 955 * @param collector the {@code Collector} describing the reduction 956 * @return the result of the reduction 957 * @see #collect(Supplier, BiConsumer, BiConsumer) 958 * @see Collectors 959 */ 960 <R, A> R collect(Collector<? super T, A, R> collector); 961 962 /** 963 * Returns the minimum element of this stream according to the provided 964 * {@code Comparator}. This is a special case of a 965 * <a href="package-summary.html#Reduction">reduction</a>. 966 * 967 * <p>This is a <a href="package-summary.html#StreamOps">terminal operation</a>. 968 * 969 * @param comparator a <a href="package-summary.html#NonInterference">non-interfering</a>, 970 * <a href="package-summary.html#Statelessness">stateless</a> 971 * {@code Comparator} to compare elements of this stream 972 * @return an {@code Optional} describing the minimum element of this stream, 973 * or an empty {@code Optional} if the stream is empty 974 * @throws NullPointerException if the minimum element is null 975 */ 976 Optional<T> min(Comparator<? super T> comparator); 977 978 /** 979 * Returns the maximum element of this stream according to the provided 980 * {@code Comparator}. This is a special case of a 981 * <a href="package-summary.html#Reduction">reduction</a>. 982 * 983 * <p>This is a <a href="package-summary.html#StreamOps">terminal 984 * operation</a>. 985 * 986 * @param comparator a <a href="package-summary.html#NonInterference">non-interfering</a>, 987 * <a href="package-summary.html#Statelessness">stateless</a> 988 * {@code Comparator} to compare elements of this stream 989 * @return an {@code Optional} describing the maximum element of this stream, 990 * or an empty {@code Optional} if the stream is empty 991 * @throws NullPointerException if the maximum element is null 992 */ 993 Optional<T> max(Comparator<? super T> comparator); 994 995 /** 996 * Returns the count of elements in this stream. This is a special case of 997 * a <a href="package-summary.html#Reduction">reduction</a> and is 998 * equivalent to: 999 * <pre>{@code 1000 * return mapToLong(e -> 1L).sum(); 1001 * }</pre> 1002 * 1003 * <p>This is a <a href="package-summary.html#StreamOps">terminal operation</a>. 1004 * 1005 * @apiNote 1006 * An implementation may choose to not execute the stream pipeline (either 1007 * sequentially or in parallel) if it is capable of computing the count 1008 * directly from the stream source. In such cases no source elements will 1009 * be traversed and no intermediate operations will be evaluated. 1010 * Behavioral parameters with side-effects, which are strongly discouraged 1011 * except for harmless cases such as debugging, may be affected. For 1012 * example, consider the following stream: 1013 * <pre>{@code 1014 * List<String> l = Arrays.asList("A", "B", "C", "D"); 1015 * long count = l.stream().peek(System.out::println).count(); 1016 * }</pre> 1017 * The number of elements covered by the stream source, a {@code List}, is 1018 * known and the intermediate operation, {@code peek}, does not inject into 1019 * or remove elements from the stream (as may be the case for 1020 * {@code flatMap} or {@code filter} operations). Thus the count is the 1021 * size of the {@code List} and there is no need to execute the pipeline 1022 * and, as a side-effect, print out the list elements. 1023 * 1024 * @return the count of elements in this stream 1025 */ 1026 long count(); 1027 1028 /** 1029 * Returns whether any elements of this stream match the provided 1030 * predicate. May not evaluate the predicate on all elements if not 1031 * necessary for determining the result. If the stream is empty then 1032 * {@code false} is returned and the predicate is not evaluated. 1033 * 1034 * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting 1035 * terminal operation</a>. 1036 * 1037 * @apiNote 1038 * This method evaluates the <em>existential quantification</em> of the 1039 * predicate over the elements of the stream (for some x P(x)). 1040 * 1041 * @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>, 1042 * <a href="package-summary.html#Statelessness">stateless</a> 1043 * predicate to apply to elements of this stream 1044 * @return {@code true} if any elements of the stream match the provided 1045 * predicate, otherwise {@code false} 1046 */ 1047 boolean anyMatch(Predicate<? super T> predicate); 1048 1049 /** 1050 * Returns whether all elements of this stream match the provided predicate. 1051 * May not evaluate the predicate on all elements if not necessary for 1052 * determining the result. If the stream is empty then {@code true} is 1053 * returned and the predicate is not evaluated. 1054 * 1055 * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting 1056 * terminal operation</a>. 1057 * 1058 * @apiNote 1059 * This method evaluates the <em>universal quantification</em> of the 1060 * predicate over the elements of the stream (for all x P(x)). If the 1061 * stream is empty, the quantification is said to be <em>vacuously 1062 * satisfied</em> and is always {@code true} (regardless of P(x)). 1063 * 1064 * @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>, 1065 * <a href="package-summary.html#Statelessness">stateless</a> 1066 * predicate to apply to elements of this stream 1067 * @return {@code true} if either all elements of the stream match the 1068 * provided predicate or the stream is empty, otherwise {@code false} 1069 */ 1070 boolean allMatch(Predicate<? super T> predicate); 1071 1072 /** 1073 * Returns whether no elements of this stream match the provided predicate. 1074 * May not evaluate the predicate on all elements if not necessary for 1075 * determining the result. If the stream is empty then {@code true} is 1076 * returned and the predicate is not evaluated. 1077 * 1078 * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting 1079 * terminal operation</a>. 1080 * 1081 * @apiNote 1082 * This method evaluates the <em>universal quantification</em> of the 1083 * negated predicate over the elements of the stream (for all x ~P(x)). If 1084 * the stream is empty, the quantification is said to be vacuously satisfied 1085 * and is always {@code true}, regardless of P(x). 1086 * 1087 * @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>, 1088 * <a href="package-summary.html#Statelessness">stateless</a> 1089 * predicate to apply to elements of this stream 1090 * @return {@code true} if either no elements of the stream match the 1091 * provided predicate or the stream is empty, otherwise {@code false} 1092 */ 1093 boolean noneMatch(Predicate<? super T> predicate); 1094 1095 /** 1096 * Returns an {@link Optional} describing the first element of this stream, 1097 * or an empty {@code Optional} if the stream is empty. If the stream has 1098 * no encounter order, then any element may be returned. 1099 * 1100 * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting 1101 * terminal operation</a>. 1102 * 1103 * @return an {@code Optional} describing the first element of this stream, 1104 * or an empty {@code Optional} if the stream is empty 1105 * @throws NullPointerException if the element selected is null 1106 */ 1107 Optional<T> findFirst(); 1108 1109 /** 1110 * Returns an {@link Optional} describing some element of the stream, or an 1111 * empty {@code Optional} if the stream is empty. 1112 * 1113 * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting 1114 * terminal operation</a>. 1115 * 1116 * <p>The behavior of this operation is explicitly nondeterministic; it is 1117 * free to select any element in the stream. This is to allow for maximal 1118 * performance in parallel operations; the cost is that multiple invocations 1119 * on the same source may not return the same result. (If a stable result 1120 * is desired, use {@link #findFirst()} instead.) 1121 * 1122 * @return an {@code Optional} describing some element of this stream, or an 1123 * empty {@code Optional} if the stream is empty 1124 * @throws NullPointerException if the element selected is null 1125 * @see #findFirst() 1126 */ 1127 Optional<T> findAny(); 1128 1129 // Static factories 1130 1131 /** 1132 * Returns a builder for a {@code Stream}. 1133 * 1134 * @param <T> type of elements 1135 * @return a stream builder 1136 */ 1137 public static<T> Builder<T> builder() { 1138 return new Streams.StreamBuilderImpl<>(); 1139 } 1140 1141 /** 1142 * Returns an empty sequential {@code Stream}. 1143 * 1144 * @param <T> the type of stream elements 1145 * @return an empty sequential stream 1146 */ 1147 public static<T> Stream<T> empty() { 1148 return StreamSupport.stream(Spliterators.<T>emptySpliterator(), false); 1149 } 1150 1151 /** 1152 * Returns a sequential {@code Stream} containing a single element. 1153 * 1154 * @param t the single element 1155 * @param <T> the type of stream elements 1156 * @return a singleton sequential stream 1157 */ 1158 public static<T> Stream<T> of(T t) { 1159 return StreamSupport.stream(new Streams.StreamBuilderImpl<>(t), false); 1160 } 1161 1162 /** 1163 * Returns a sequential {@code Stream} containing a single element, if 1164 * non-null, otherwise returns an empty {@code Stream}. 1165 * 1166 * @param t the single element 1167 * @param <T> the type of stream elements 1168 * @return a stream with a single element if the specified element 1169 * is non-null, otherwise an empty stream 1170 * @since 9 1171 */ 1172 public static<T> Stream<T> ofNullable(T t) { 1173 return t == null ? Stream.empty() 1174 : StreamSupport.stream(new Streams.StreamBuilderImpl<>(t), false); 1175 } 1176 1177 /** 1178 * Returns a sequential ordered stream whose elements are the specified values. 1179 * 1180 * @param <T> the type of stream elements 1181 * @param values the elements of the new stream 1182 * @return the new stream 1183 */ 1184 @SafeVarargs 1185 @SuppressWarnings("varargs") // Creating a stream from an array is safe 1186 public static<T> Stream<T> of(T... values) { 1187 return Arrays.stream(values); 1188 } 1189 1190 /** 1191 * Returns an infinite sequential ordered {@code Stream} produced by iterative 1192 * application of a function {@code f} to an initial element {@code seed}, 1193 * producing a {@code Stream} consisting of {@code seed}, {@code f(seed)}, 1194 * {@code f(f(seed))}, etc. 1195 * 1196 * <p>The first element (position {@code 0}) in the {@code Stream} will be 1197 * the provided {@code seed}. For {@code n > 0}, the element at position 1198 * {@code n}, will be the result of applying the function {@code f} to the 1199 * element at position {@code n - 1}. 1200 * 1201 * <p>The action of applying {@code f} for one element 1202 * <a href="../concurrent/package-summary.html#MemoryVisibility"><i>happens-before</i></a> 1203 * the action of applying {@code f} for subsequent elements. For any given 1204 * element the action may be performed in whatever thread the library 1205 * chooses. 1206 * 1207 * @param <T> the type of stream elements 1208 * @param seed the initial element 1209 * @param f a function to be applied to the previous element to produce 1210 * a new element 1211 * @return a new sequential {@code Stream} 1212 */ 1213 public static<T> Stream<T> iterate(final T seed, final UnaryOperator<T> f) { 1214 Objects.requireNonNull(f); 1215 Spliterator<T> spliterator = new Spliterators.AbstractSpliterator<>(Long.MAX_VALUE, 1216 Spliterator.ORDERED | Spliterator.IMMUTABLE) { 1217 T prev; 1218 boolean started; 1219 1220 @Override 1221 public boolean tryAdvance(Consumer<? super T> action) { 1222 Objects.requireNonNull(action); 1223 T t; 1224 if (started) 1225 t = f.apply(prev); 1226 else { 1227 t = seed; 1228 started = true; 1229 } 1230 action.accept(prev = t); 1231 return true; 1232 } 1233 }; 1234 return StreamSupport.stream(spliterator, false); 1235 } 1236 1237 /** 1238 * Returns a sequential ordered {@code Stream} produced by iterative 1239 * application of the given {@code next} function to an initial element, 1240 * conditioned on satisfying the given {@code hasNext} predicate. The 1241 * stream terminates as soon as the {@code hasNext} predicate returns false. 1242 * 1243 * <p>{@code Stream.iterate} should produce the same sequence of elements as 1244 * produced by the corresponding for-loop: 1245 * <pre>{@code 1246 * for (T index=seed; hasNext.test(index); index = next.apply(index)) { 1247 * ... 1248 * } 1249 * }</pre> 1250 * 1251 * <p>The resulting sequence may be empty if the {@code hasNext} predicate 1252 * does not hold on the seed value. Otherwise the first element will be the 1253 * supplied {@code seed} value, the next element (if present) will be the 1254 * result of applying the {@code next} function to the {@code seed} value, 1255 * and so on iteratively until the {@code hasNext} predicate indicates that 1256 * the stream should terminate. 1257 * 1258 * <p>The action of applying the {@code hasNext} predicate to an element 1259 * <a href="../concurrent/package-summary.html#MemoryVisibility"><i>happens-before</i></a> 1260 * the action of applying the {@code next} function to that element. The 1261 * action of applying the {@code next} function for one element 1262 * <i>happens-before</i> the action of applying the {@code hasNext} 1263 * predicate for subsequent elements. For any given element an action may 1264 * be performed in whatever thread the library chooses. 1265 * 1266 * @param <T> the type of stream elements 1267 * @param seed the initial element 1268 * @param hasNext a predicate to apply to elements to determine when the 1269 * stream must terminate. 1270 * @param next a function to be applied to the previous element to produce 1271 * a new element 1272 * @return a new sequential {@code Stream} 1273 * @since 9 1274 */ 1275 public static<T> Stream<T> iterate(T seed, Predicate<? super T> hasNext, UnaryOperator<T> next) { 1276 Objects.requireNonNull(next); 1277 Objects.requireNonNull(hasNext); 1278 Spliterator<T> spliterator = new Spliterators.AbstractSpliterator<>(Long.MAX_VALUE, 1279 Spliterator.ORDERED | Spliterator.IMMUTABLE) { 1280 T prev; 1281 boolean started, finished; 1282 1283 @Override 1284 public boolean tryAdvance(Consumer<? super T> action) { 1285 Objects.requireNonNull(action); 1286 if (finished) 1287 return false; 1288 T t; 1289 if (started) 1290 t = next.apply(prev); 1291 else { 1292 t = seed; 1293 started = true; 1294 } 1295 if (!hasNext.test(t)) { 1296 prev = null; 1297 finished = true; 1298 return false; 1299 } 1300 action.accept(prev = t); 1301 return true; 1302 } 1303 1304 @Override 1305 public void forEachRemaining(Consumer<? super T> action) { 1306 Objects.requireNonNull(action); 1307 if (finished) 1308 return; 1309 finished = true; 1310 T t = started ? next.apply(prev) : seed; 1311 prev = null; 1312 while (hasNext.test(t)) { 1313 action.accept(t); 1314 t = next.apply(t); 1315 } 1316 } 1317 }; 1318 return StreamSupport.stream(spliterator, false); 1319 } 1320 1321 /** 1322 * Returns an infinite sequential unordered stream where each element is 1323 * generated by the provided {@code Supplier}. This is suitable for 1324 * generating constant streams, streams of random elements, etc. 1325 * 1326 * @param <T> the type of stream elements 1327 * @param s the {@code Supplier} of generated elements 1328 * @return a new infinite sequential unordered {@code Stream} 1329 */ 1330 public static<T> Stream<T> generate(Supplier<? extends T> s) { 1331 Objects.requireNonNull(s); 1332 return StreamSupport.stream( 1333 new StreamSpliterators.InfiniteSupplyingSpliterator.OfRef<>(Long.MAX_VALUE, s), false); 1334 } 1335 1336 /** 1337 * Creates a lazily concatenated stream whose elements are all the 1338 * elements of the first stream followed by all the elements of the 1339 * second stream. The resulting stream is ordered if both 1340 * of the input streams are ordered, and parallel if either of the input 1341 * streams is parallel. When the resulting stream is closed, the close 1342 * handlers for both input streams are invoked. 1343 * 1344 * @implNote 1345 * Use caution when constructing streams from repeated concatenation. 1346 * Accessing an element of a deeply concatenated stream can result in deep 1347 * call chains, or even {@code StackOverflowError}. 1348 * 1349 * <p>Subsequent changes to the sequential/parallel execution mode of the 1350 * returned stream are not guaranteed to be propagated to the input streams. 1351 * 1352 * @param <T> The type of stream elements 1353 * @param a the first stream 1354 * @param b the second stream 1355 * @return the concatenation of the two input streams 1356 */ 1357 public static <T> Stream<T> concat(Stream<? extends T> a, Stream<? extends T> b) { 1358 Objects.requireNonNull(a); 1359 Objects.requireNonNull(b); 1360 1361 @SuppressWarnings("unchecked") 1362 Spliterator<T> split = new Streams.ConcatSpliterator.OfRef<>( 1363 (Spliterator<T>) a.spliterator(), (Spliterator<T>) b.spliterator()); 1364 Stream<T> stream = StreamSupport.stream(split, a.isParallel() || b.isParallel()); 1365 return stream.onClose(Streams.composedClose(a, b)); 1366 } 1367 1368 /** 1369 * A mutable builder for a {@code Stream}. This allows the creation of a 1370 * {@code Stream} by generating elements individually and adding them to the 1371 * {@code Builder} (without the copying overhead that comes from using 1372 * an {@code ArrayList} as a temporary buffer.) 1373 * 1374 * <p>A stream builder has a lifecycle, which starts in a building 1375 * phase, during which elements can be added, and then transitions to a built 1376 * phase, after which elements may not be added. The built phase begins 1377 * when the {@link #build()} method is called, which creates an ordered 1378 * {@code Stream} whose elements are the elements that were added to the stream 1379 * builder, in the order they were added. 1380 * 1381 * @param <T> the type of stream elements 1382 * @see Stream#builder() 1383 * @since 1.8 1384 */ 1385 public interface Builder<T> extends Consumer<T> { 1386 1387 /** 1388 * Adds an element to the stream being built. 1389 * 1390 * @throws IllegalStateException if the builder has already transitioned to 1391 * the built state 1392 */ 1393 @Override 1394 void accept(T t); 1395 1396 /** 1397 * Adds an element to the stream being built. 1398 * 1399 * @implSpec 1400 * The default implementation behaves as if: 1401 * <pre>{@code 1402 * accept(t) 1403 * return this; 1404 * }</pre> 1405 * 1406 * @param t the element to add 1407 * @return {@code this} builder 1408 * @throws IllegalStateException if the builder has already transitioned to 1409 * the built state 1410 */ 1411 default Builder<T> add(T t) { 1412 accept(t); 1413 return this; 1414 } 1415 1416 /** 1417 * Builds the stream, transitioning this builder to the built state. 1418 * An {@code IllegalStateException} is thrown if there are further attempts 1419 * to operate on the builder after it has entered the built state. 1420 * 1421 * @return the built stream 1422 * @throws IllegalStateException if the builder has already transitioned to 1423 * the built state 1424 */ 1425 Stream<T> build(); 1426 1427 } 1428 }