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