1 /* 2 * Copyright (c) 2013, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 package java.util.stream; 26 27 import java.nio.charset.Charset; 28 import java.nio.file.Files; 29 import java.nio.file.Path; 30 import java.util.Arrays; 31 import java.util.Collection; 32 import java.util.LongSummaryStatistics; 33 import java.util.Objects; 34 import java.util.OptionalDouble; 35 import java.util.OptionalLong; 36 import java.util.PrimitiveIterator; 37 import java.util.Spliterator; 38 import java.util.Spliterators; 39 import java.util.concurrent.ConcurrentHashMap; 40 import java.util.function.BiConsumer; 41 import java.util.function.Function; 42 import java.util.function.LongBinaryOperator; 43 import java.util.function.LongConsumer; 44 import java.util.function.LongFunction; 45 import java.util.function.LongPredicate; 46 import java.util.function.LongSupplier; 47 import java.util.function.LongToDoubleFunction; 48 import java.util.function.LongToIntFunction; 49 import java.util.function.LongUnaryOperator; 50 import java.util.function.ObjLongConsumer; 51 import java.util.function.Supplier; 52 53 /** 54 * A sequence of elements supporting sequential and parallel aggregate 55 * operations. The following example illustrates an aggregate operation using 56 * {@link Stream} and {@link LongStream}: 57 * 58 * <pre>{@code 59 * long sum = widgets.stream() 60 * .filter(w -> w.getColor() == RED) 61 * .mapToLong(w -> w.getWeight()) 62 * .sum(); 63 * }</pre> 64 * 65 * In this example, {@code widgets} is a {@code Collection<Widget>}. We create 66 * a stream of {@code Widget} objects via {@link Collection#stream Collection.stream()}, 67 * filter it to produce a stream containing only the red widgets, and then 68 * transform it into a stream of {@code long} values representing the weight of 69 * each red widget. Then this stream is summed to produce a total weight. 70 * 71 * <p>To perform a computation, stream 72 * <a href="package-summary.html#StreamOps">operations</a> are composed into a 73 * <em>stream pipeline</em>. A stream pipeline consists of a source (which 74 * might be an array, a collection, a generator function, an IO channel, 75 * etc), zero or more <em>intermediate operations</em> (which transform a 76 * stream into another stream, such as {@link LongStream#filter(LongPredicate)}), and a 77 * <em>terminal operation</em> (which produces a result or side-effect, such 78 * as {@link LongStream#sum()} or {@link LongStream#forEach(LongConsumer)}). 79 * Streams are lazy; computation on the source data is only performed when the 80 * terminal operation is initiated, and source elements are consumed only 81 * as needed. 82 * 83 * <p>Collections and streams, while bearing some superficial similarities, 84 * have different goals. Collections are primarily concerned with the efficient 85 * management of, and access to, their elements. By contrast, streams do not 86 * provide a means to directly access or manipulate their elements, and are 87 * instead concerned with declaratively describing their source and the 88 * computational operations which will be performed in aggregate on that source. 89 * However, if the provided stream operations do not offer the desired 90 * functionality, the {@link #iterator()} and {@link #spliterator()} operations 91 * can be used to perform a controlled traversal. 92 * 93 * <p>A stream pipeline, like the "widgets" example above, can be viewed as 94 * a <em>query</em> on the stream source. Unless the source was explicitly 95 * designed for concurrent modification (such as a {@link ConcurrentHashMap}), 96 * unpredictable or erroneous behavior may result from modifying the stream 97 * source while it is being queried. 98 * 99 * <p>Most stream operations accept parameters that describe user-specified 100 * behavior, such as the lambda expression {@code w -> w.getWeight()} passed to 101 * {@code mapToLong} in the example above. Such parameters are always instances 102 * of a <a href="../function/package-summary.html">functional interface</a> such 103 * as {@link java.util.function.Function}, and are often lambda expressions or 104 * method references. These parameters can never be null, should not modify the 105 * stream source, and should be 106 * <a href="package-summary.html#NonInterference">effectively stateless</a> 107 * (their result should not depend on any state that might change during 108 * execution of the stream pipeline.) 109 * 110 * <p>A stream should be operated on (invoking an intermediate or terminal stream 111 * operation) only once. This rules out, for example, "forked" streams, where 112 * the same source feeds two or more pipelines, or multiple traversals of the 113 * same stream. A stream implementation may throw {@link IllegalStateException} 114 * if it detects that the stream is being reused. However, since some stream 115 * operations may return their receiver rather than a new stream object, it may 116 * not be possible to detect reuse in all cases. 117 * 118 * <p>Streams have a {@link #close()} method and implement {@link AutoCloseable}, 119 * but nearly all stream instances do not actually need to be closed after use. 120 * Generally, only streams whose source is an IO channel (such as those returned 121 * by {@link Files#lines(Path, Charset)}) will require closing. Most streams 122 * are backed by collections, arrays, or generating functions, which require no 123 * special resource management. (If a stream does require closing, it can be 124 * declared as a resource in a {@code try}-with-resources statement.) 125 * 126 * <p>Stream pipelines may execute either sequentially or in 127 * <a href="package-summary.html#Parallelism">parallel</a>. This 128 * execution mode is a property of the stream. Streams are created 129 * with an initial choice of sequential or parallel execution. (For example, 130 * {@link Collection#stream() Collection.stream()} creates a sequential stream, 131 * and {@link Collection#parallelStream() Collection.parallelStream()} creates 132 * a parallel one.) This choice of execution mode may be modified by the 133 * {@link #sequential()} or {@link #parallel()} methods, and may be queried with 134 * the {@link #isParallel()} method. 135 * 136 * @since 1.8 137 * @see <a href="package-summary.html">java.util.stream</a> 138 */ 139 public interface LongStream extends BaseStream<Long, LongStream> { 140 141 /** 142 * Returns a stream consisting of the elements of this stream that match 143 * the given predicate. 144 * 145 * <p>This is an <a href="package-summary.html#StreamOps">intermediate 146 * operation</a>. 147 * 148 * @param predicate a <a href="package-summary.html#NonInterference"> 149 * non-interfering, stateless</a> predicate to apply to 150 * each element to determine if it should be included 151 * @return the new stream 152 */ 153 LongStream filter(LongPredicate predicate); 154 155 /** 156 * Returns a stream consisting of the results of applying the given 157 * function to the elements of this stream. 158 * 159 * <p>This is an <a href="package-summary.html#StreamOps">intermediate 160 * operation</a>. 161 * 162 * @param mapper a <a href="package-summary.html#NonInterference"> 163 * non-interfering, stateless</a> function to apply to each 164 * element 165 * @return the new stream 166 */ 167 LongStream map(LongUnaryOperator mapper); 168 169 /** 170 * Returns an object-valued {@code Stream} consisting of the results of 171 * applying the given function to the elements of this stream. 172 * 173 * <p>This is an <a href="package-summary.html#StreamOps"> 174 * intermediate operation</a>. 175 * 176 * @param <U> the element type of the new stream 177 * @param mapper a <a href="package-summary.html#NonInterference"> 178 * non-interfering, stateless</a> function to apply to each 179 * element 180 * @return the new stream 181 */ 182 <U> Stream<U> mapToObj(LongFunction<? extends U> mapper); 183 184 /** 185 * Returns an {@code IntStream} consisting of the results of applying the 186 * given 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 mapper a <a href="package-summary.html#NonInterference"> 192 * non-interfering, stateless</a> function to apply to each 193 * element 194 * @return the new stream 195 */ 196 IntStream mapToInt(LongToIntFunction mapper); 197 198 /** 199 * Returns a {@code DoubleStream} consisting of the results of applying the 200 * given function to the elements of this stream. 201 * 202 * <p>This is an <a href="package-summary.html#StreamOps">intermediate 203 * operation</a>. 204 * 205 * @param mapper a <a href="package-summary.html#NonInterference"> 206 * non-interfering, stateless</a> function to apply to each 207 * element 208 * @return the new stream 209 */ 210 DoubleStream mapToDouble(LongToDoubleFunction mapper); 211 212 /** 213 * Returns a stream consisting of the results of replacing each element of 214 * this stream with the contents of the stream produced by applying the 215 * provided mapping function to each element. (If the result of the mapping 216 * function is {@code null}, this is treated as if the result was an empty 217 * stream.) 218 * 219 * <p>This is an <a href="package-summary.html#StreamOps">intermediate 220 * operation</a>. 221 * 222 * @param mapper a <a href="package-summary.html#NonInterference"> 223 * non-interfering, stateless</a> function to apply to 224 * each element which produces an {@code LongStream} of new 225 * values 226 * @return the new stream 227 * @see Stream#flatMap(Function) 228 */ 229 LongStream flatMap(LongFunction<? extends LongStream> mapper); 230 231 /** 232 * Returns a stream consisting of the distinct elements of this stream. 233 * 234 * <p>This is a <a href="package-summary.html#StreamOps">stateful 235 * intermediate operation</a>. 236 * 237 * @return the new stream 238 */ 239 LongStream distinct(); 240 241 /** 242 * Returns a stream consisting of the elements of this stream in sorted 243 * order. 244 * 245 * <p>This is a <a href="package-summary.html#StreamOps">stateful 246 * intermediate operation</a>. 247 * 248 * @return the new stream 249 */ 250 LongStream sorted(); 251 252 /** 253 * Returns a stream consisting of the elements of this stream, additionally 254 * performing the provided action on each element as elements are consumed 255 * from the resulting stream. 256 * 257 * <p>This is an <a href="package-summary.html#StreamOps">intermediate 258 * operation</a>. 259 * 260 * <p>For parallel stream pipelines, the action may be called at 261 * whatever time and in whatever thread the element is made available by the 262 * upstream operation. If the action modifies shared state, 263 * it is responsible for providing the required synchronization. 264 * 265 * @apiNote This method exists mainly to support debugging, where you want 266 * to see the elements as they flow past a certain point in a pipeline: 267 * <pre>{@code 268 * list.stream() 269 * .filter(filteringFunction) 270 * .peek(e -> System.out.println("Filtered value: " + e)); 271 * .map(mappingFunction) 272 * .peek(e -> System.out.println("Mapped value: " + e)); 273 * .collect(Collectors.toLongSummaryStastistics()); 274 * }</pre> 275 * 276 * @param action a <a href="package-summary.html#NonInterference"> 277 * non-interfering</a> action to perform on the elements as 278 * they are consumed from the stream 279 * @return the new stream 280 */ 281 LongStream peek(LongConsumer action); 282 283 /** 284 * Returns a stream consisting of the elements of this stream, truncated 285 * to be no longer than {@code maxSize} in length. 286 * 287 * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting 288 * stateful intermediate operation</a>. 289 * 290 * @apiNote 291 * While {@code limit()} is generally a cheap operation on sequential 292 * stream pipelines, it can be quite expensive on ordered parallel pipelines, 293 * especially for large values of {@code maxSize}, since {@code limit(n)} 294 * is constrained to return not just any <em>n</em> elements, but the 295 * <em>first n</em> elements in the encounter order. Using an unordered 296 * stream source (such as {@link #generate(LongSupplier)}) or removing the 297 * ordering constraint with {@link #unordered()} may result in significant 298 * speedups of {@code limit()} in parallel pipelines, if the semantics of 299 * your situation permit. If consistency with encounter order is required, 300 * and you are experiencing poor performance or memory utilization with 301 * {@code limit()} in parallel pipelines, switching to sequential execution 302 * with {@link #sequential()} may improve performance. 303 * 304 * @param maxSize the number of elements the stream should be limited to 305 * @return the new stream 306 * @throws IllegalArgumentException if {@code maxSize} is negative 307 */ 308 LongStream limit(long maxSize); 309 310 /** 311 * Returns a stream consisting of the remaining elements of this stream 312 * after discarding the first {@code n} elements of the stream. 313 * If this stream contains fewer than {@code n} elements then an 314 * empty stream will be returned. 315 * 316 * <p>This is a <a href="package-summary.html#StreamOps">stateful 317 * intermediate operation</a>. 318 * 319 * @apiNote 320 * While {@code skip()} is generally a cheap operation on sequential 321 * stream pipelines, it can be quite expensive on ordered parallel pipelines, 322 * especially for large values of {@code n}, since {@code skip(n)} 323 * is constrained to skip not just any <em>n</em> elements, but the 324 * <em>first n</em> elements in the encounter order. Using an unordered 325 * stream source (such as {@link #generate(Supplier)}) or removing the 326 * ordering constraint with {@link #unordered()} may result in significant 327 * speedups of {@code skip()} in parallel pipelines, if the semantics of 328 * your situation permit. If consistency with encounter order is required, 329 * and you are experiencing poor performance or memory utilization with 330 * {@code skip()} in parallel pipelines, switching to sequential execution 331 * with {@link #sequential()} may improve performance. 332 * 333 * @param n the number of leading elements to skip 334 * @return the new stream 335 * @throws IllegalArgumentException if {@code n} is negative 336 */ 337 LongStream skip(long n); 338 339 /** 340 * Performs an action for each element of this stream. 341 * 342 * <p>This is a <a href="package-summary.html#StreamOps">terminal 343 * operation</a>. 344 * 345 * <p>For parallel stream pipelines, this operation does <em>not</em> 346 * guarantee to respect the encounter order of the stream, as doing so 347 * would sacrifice the benefit of parallelism. For any given element, the 348 * action may be performed at whatever time and in whatever thread the 349 * library chooses. If the action accesses shared state, it is 350 * responsible for providing the required synchronization. 351 * 352 * @param action a <a href="package-summary.html#NonInterference"> 353 * non-interfering</a> action to perform on the elements 354 */ 355 void forEach(LongConsumer action); 356 357 /** 358 * Performs an action for each element of this stream, guaranteeing that 359 * each element is processed in encounter order for streams that have a 360 * defined encounter order. 361 * 362 * <p>This is a <a href="package-summary.html#StreamOps">terminal 363 * operation</a>. 364 * 365 * @param action a <a href="package-summary.html#NonInterference"> 366 * non-interfering</a> action to perform on the elements 367 * @see #forEach(LongConsumer) 368 */ 369 void forEachOrdered(LongConsumer action); 370 371 /** 372 * Returns an array containing the elements of this stream. 373 * 374 * <p>This is a <a href="package-summary.html#StreamOps">terminal 375 * operation</a>. 376 * 377 * @return an array containing the elements of this stream 378 */ 379 long[] toArray(); 380 381 /** 382 * Performs a <a href="package-summary.html#Reduction">reduction</a> on the 383 * elements of this stream, using the provided identity value and an 384 * <a href="package-summary.html#Associativity">associative</a> 385 * accumulation function, and returns the reduced value. This is equivalent 386 * to: 387 * <pre>{@code 388 * long result = identity; 389 * for (long element : this stream) 390 * result = accumulator.apply(result, element) 391 * return result; 392 * }</pre> 393 * 394 * but is not constrained to execute sequentially. 395 * 396 * <p>The {@code identity} value must be an identity for the accumulator 397 * function. This means that for all {@code x}, 398 * {@code accumulator.apply(identity, x)} is equal to {@code x}. 399 * The {@code accumulator} function must be an 400 * <a href="package-summary.html#Associativity">associative</a> function. 401 * 402 * <p>This is a <a href="package-summary.html#StreamOps">terminal 403 * operation</a>. 404 * 405 * @apiNote Sum, min, max, and average are all special cases of reduction. 406 * Summing a stream of numbers can be expressed as: 407 * 408 * <pre>{@code 409 * long sum = integers.reduce(0, (a, b) -> a+b); 410 * }</pre> 411 * 412 * or more compactly: 413 * 414 * <pre>{@code 415 * long sum = integers.reduce(0, Long::sum); 416 * }</pre> 417 * 418 * <p>While this may seem a more roundabout way to perform an aggregation 419 * compared to simply mutating a running total in a loop, reduction 420 * operations parallelize more gracefully, without needing additional 421 * synchronization and with greatly reduced risk of data races. 422 * 423 * @param identity the identity value for the accumulating function 424 * @param op an <a href="package-summary.html#Associativity">associative</a> 425 * <a href="package-summary.html#NonInterference">non-interfering, 426 * stateless</a> function for combining two values 427 * @return the result of the reduction 428 * @see #sum() 429 * @see #min() 430 * @see #max() 431 * @see #average() 432 */ 433 long reduce(long identity, LongBinaryOperator op); 434 435 /** 436 * Performs a <a href="package-summary.html#Reduction">reduction</a> on the 437 * elements of this stream, using an 438 * <a href="package-summary.html#Associativity">associative</a> accumulation 439 * function, and returns an {@code OptionalLong} describing the reduced value, 440 * if any. This is equivalent to: 441 * <pre>{@code 442 * boolean foundAny = false; 443 * long result = null; 444 * for (long element : this stream) { 445 * if (!foundAny) { 446 * foundAny = true; 447 * result = element; 448 * } 449 * else 450 * result = accumulator.apply(result, element); 451 * } 452 * return foundAny ? OptionalLong.of(result) : OptionalLong.empty(); 453 * }</pre> 454 * 455 * but is not constrained to execute sequentially. 456 * 457 * <p>The {@code accumulator} function must be an 458 * <a href="package-summary.html#Associativity">associative</a> function. 459 * 460 * <p>This is a <a href="package-summary.html#StreamOps">terminal 461 * operation</a>. 462 * 463 * @param op an <a href="package-summary.html#Associativity">associative</a> 464 * <a href="package-summary.html#NonInterference">non-interfering, 465 * stateless</a> function for combining two values 466 * @return the result of the reduction 467 * @see #reduce(long, LongBinaryOperator) 468 */ 469 OptionalLong reduce(LongBinaryOperator op); 470 471 /** 472 * Performs a <a href="package-summary.html#MutableReduction">mutable 473 * reduction</a> operation on the elements of this stream. A mutable 474 * reduction is one in which the reduced value is a mutable result container, 475 * such as an {@code ArrayList}, and elements are incorporated by updating 476 * the state of the result rather than by replacing the result. This 477 * produces a result equivalent to: 478 * <pre>{@code 479 * R result = supplier.get(); 480 * for (long element : this stream) 481 * accumulator.accept(result, element); 482 * return result; 483 * }</pre> 484 * 485 * <p>Like {@link #reduce(long, LongBinaryOperator)}, {@code collect} operations 486 * can be parallelized without requiring additional synchronization. 487 * 488 * <p>This is a <a href="package-summary.html#StreamOps">terminal 489 * operation</a>. 490 * 491 * @param <R> type of the result 492 * @param supplier a function that creates a new result container. For a 493 * parallel execution, this function may be called 494 * multiple times and must return a fresh value each time. 495 * @param accumulator an <a href="package-summary.html#Associativity">associative</a> 496 * <a href="package-summary.html#NonInterference">non-interfering, 497 * stateless</a> function for incorporating an additional 498 * element into a result 499 * @param combiner an <a href="package-summary.html#Associativity">associative</a> 500 * <a href="package-summary.html#NonInterference">non-interfering, 501 * stateless</a> function for combining two values, which 502 * must be compatible with the accumulator function 503 * @return the result of the reduction 504 * @see Stream#collect(Supplier, BiConsumer, BiConsumer) 505 */ 506 <R> R collect(Supplier<R> supplier, 507 ObjLongConsumer<R> accumulator, 508 BiConsumer<R, R> combiner); 509 510 /** 511 * Returns the sum of elements in this stream. This is a special case 512 * of a <a href="package-summary.html#Reduction">reduction</a> 513 * and is equivalent to: 514 * <pre>{@code 515 * return reduce(0, Long::sum); 516 * }</pre> 517 * 518 * <p>This is a <a href="package-summary.html#StreamOps">terminal 519 * operation</a>. 520 * 521 * @return the sum of elements in this stream 522 */ 523 long sum(); 524 525 /** 526 * Returns an {@code OptionalLong} describing the minimum element of this 527 * stream, or an empty optional if this stream is empty. This is a special 528 * case of a <a href="package-summary.html#Reduction">reduction</a> 529 * and is equivalent to: 530 * <pre>{@code 531 * return reduce(Long::min); 532 * }</pre> 533 * 534 * <p>This is a <a href="package-summary.html#StreamOps">terminal operation</a>. 535 * 536 * @return an {@code OptionalLong} containing the minimum element of this 537 * stream, or an empty {@code OptionalLong} if the stream is empty 538 */ 539 OptionalLong min(); 540 541 /** 542 * Returns an {@code OptionalLong} describing the maximum element of this 543 * stream, or an empty optional if this stream is empty. This is a special 544 * case of a <a href="package-summary.html#Reduction">reduction</a> 545 * and is equivalent to: 546 * <pre>{@code 547 * return reduce(Long::max); 548 * }</pre> 549 * 550 * <p>This is a <a href="package-summary.html#StreamOps">terminal 551 * operation</a>. 552 * 553 * @return an {@code OptionalLong} containing the maximum element of this 554 * stream, or an empty {@code OptionalLong} if the stream is empty 555 */ 556 OptionalLong max(); 557 558 /** 559 * Returns the count of elements in this stream. This is a special case of 560 * a <a href="package-summary.html#Reduction">reduction</a> and is 561 * equivalent to: 562 * <pre>{@code 563 * return map(e -> 1L).sum(); 564 * }</pre> 565 * 566 * <p>This is a <a href="package-summary.html#StreamOps">terminal operation</a>. 567 * 568 * @return the count of elements in this stream 569 */ 570 long count(); 571 572 /** 573 * Returns an {@code OptionalDouble} describing the arithmetic mean of elements of 574 * this stream, or an empty optional if this stream is empty. This is a 575 * special case of a 576 * <a href="package-summary.html#Reduction">reduction</a>. 577 * 578 * <p>This is a <a href="package-summary.html#StreamOps">terminal 579 * operation</a>. 580 * 581 * @return an {@code OptionalDouble} containing the average element of this 582 * stream, or an empty optional if the stream is empty 583 */ 584 OptionalDouble average(); 585 586 /** 587 * Returns a {@code LongSummaryStatistics} describing various summary data 588 * about the elements of this stream. This is a special case of a 589 * <a href="package-summary.html#Reduction">reduction</a>. 590 * 591 * <p>This is a <a href="package-summary.html#StreamOps">terminal 592 * operation</a>. 593 * 594 * @return a {@code LongSummaryStatistics} describing various summary data 595 * about the elements of this stream 596 */ 597 LongSummaryStatistics summaryStatistics(); 598 599 /** 600 * Returns whether any elements of this stream match the provided 601 * predicate. May not evaluate the predicate on all elements if not 602 * necessary for determining the result. 603 * 604 * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting 605 * terminal operation</a>. 606 * 607 * @param predicate a <a href="package-summary.html#NonInterference">non-interfering, 608 * stateless</a> predicate to apply to elements of this 609 * stream 610 * @return {@code true} if any elements of the stream match the provided 611 * predicate otherwise {@code false} 612 */ 613 boolean anyMatch(LongPredicate predicate); 614 615 /** 616 * Returns whether all elements of this stream match the provided predicate. 617 * May not evaluate the predicate on all elements if not necessary for 618 * determining the result. 619 * 620 * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting 621 * terminal operation</a>. 622 * 623 * @param predicate a <a href="package-summary.html#NonInterference">non-interfering, 624 * stateless</a> predicate to apply to elements of this 625 * stream 626 * @return {@code true} if all elements of the stream match the provided 627 * predicate otherwise {@code false} 628 */ 629 boolean allMatch(LongPredicate predicate); 630 631 /** 632 * Returns whether no elements of this stream match the provided predicate. 633 * May not evaluate the predicate on all elements if not necessary for 634 * determining the result. 635 * 636 * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting 637 * terminal operation</a>. 638 * 639 * @param predicate a <a href="package-summary.html#NonInterference">non-interfering, 640 * stateless</a> predicate to apply to elements of this 641 * stream 642 * @return {@code true} if no elements of the stream match the provided 643 * predicate otherwise {@code false} 644 */ 645 boolean noneMatch(LongPredicate predicate); 646 647 /** 648 * Returns an {@link OptionalLong} describing the first element of this 649 * stream, or an empty {@code OptionalLong} if the stream is empty. If the 650 * stream has no encounter order, then any element may be returned. 651 * 652 * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting 653 * terminal operation</a>. 654 * 655 * @return an {@code OptionalLong} describing the first element of this 656 * stream, or an empty {@code OptionalLong} if the stream is empty 657 */ 658 OptionalLong findFirst(); 659 660 /** 661 * Returns an {@link OptionalLong} describing some element of the stream, or 662 * an empty {@code OptionalLong} if the stream is empty. 663 * 664 * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting 665 * terminal operation</a>. 666 * 667 * <p>The behavior of this operation is explicitly nondeterministic; it is 668 * free to select any element in the stream. This is to allow for maximal 669 * performance in parallel operations; the cost is that multiple invocations 670 * on the same source may not return the same result. (If a stable result 671 * is desired, use {@link #findFirst()} instead.) 672 * 673 * @return an {@code OptionalLong} describing some element of this stream, 674 * or an empty {@code OptionalLong} if the stream is empty 675 * @see #findFirst() 676 */ 677 OptionalLong findAny(); 678 679 /** 680 * Returns a {@code DoubleStream} consisting of the elements of this stream, 681 * converted to {@code double}. 682 * 683 * <p>This is an <a href="package-summary.html#StreamOps">intermediate 684 * operation</a>. 685 * 686 * @return a {@code DoubleStream} consisting of the elements of this stream, 687 * converted to {@code double} 688 */ 689 DoubleStream asDoubleStream(); 690 691 /** 692 * Returns a {@code Stream} consisting of the elements of this stream, 693 * each boxed to a {@code Long}. 694 * 695 * <p>This is an <a href="package-summary.html#StreamOps">intermediate 696 * operation</a>. 697 * 698 * @return a {@code Stream} consistent of the elements of this stream, 699 * each boxed to {@code Long} 700 */ 701 Stream<Long> boxed(); 702 703 @Override 704 LongStream sequential(); 705 706 @Override 707 LongStream parallel(); 708 709 @Override 710 PrimitiveIterator.OfLong iterator(); 711 712 @Override 713 Spliterator.OfLong spliterator(); 714 715 // Static factories 716 717 /** 718 * Returns a builder for a {@code LongStream}. 719 * 720 * @return a stream builder 721 */ 722 public static Builder builder() { 723 return new Streams.LongStreamBuilderImpl(); 724 } 725 726 /** 727 * Returns an empty sequential {@code LongStream}. 728 * 729 * @return an empty sequential stream 730 */ 731 public static LongStream empty() { 732 return StreamSupport.longStream(Spliterators.emptyLongSpliterator(), false); 733 } 734 735 /** 736 * Returns a sequential {@code LongStream} containing a single element. 737 * 738 * @param t the single element 739 * @return a singleton sequential stream 740 */ 741 public static LongStream of(long t) { 742 return StreamSupport.longStream(new Streams.LongStreamBuilderImpl(t), false); 743 } 744 745 /** 746 * Returns a sequential ordered stream whose elements are the specified values. 747 * 748 * @param values the elements of the new stream 749 * @return the new stream 750 */ 751 public static LongStream of(long... values) { 752 return Arrays.stream(values); 753 } 754 755 /** 756 * Returns an infinite sequential ordered {@code LongStream} produced by iterative 757 * application of a function {@code f} to an initial element {@code seed}, 758 * producing a {@code Stream} consisting of {@code seed}, {@code f(seed)}, 759 * {@code f(f(seed))}, etc. 760 * 761 * <p>The first element (position {@code 0}) in the {@code LongStream} will 762 * be the provided {@code seed}. For {@code n > 0}, the element at position 763 * {@code n}, will be the result of applying the function {@code f} to the 764 * element at position {@code n - 1}. 765 * 766 * @param seed the initial element 767 * @param f a function to be applied to to the previous element to produce 768 * a new element 769 * @return a new sequential {@code LongStream} 770 */ 771 public static LongStream iterate(final long seed, final LongUnaryOperator f) { 772 Objects.requireNonNull(f); 773 final PrimitiveIterator.OfLong iterator = new PrimitiveIterator.OfLong() { 774 long t = seed; 775 776 @Override 777 public boolean hasNext() { 778 return true; 779 } 780 781 @Override 782 public long nextLong() { 783 long v = t; 784 t = f.applyAsLong(t); 785 return v; 786 } 787 }; 788 return StreamSupport.longStream(Spliterators.spliteratorUnknownSize( 789 iterator, 790 Spliterator.ORDERED | Spliterator.IMMUTABLE | Spliterator.NONNULL), false); 791 } 792 793 /** 794 * Returns a sequential stream where each element is generated by 795 * the provided {@code LongSupplier}. This is suitable for generating 796 * constant streams, streams of random elements, etc. 797 * 798 * @param s the {@code LongSupplier} for generated elements 799 * @return a new sequential {@code LongStream} 800 */ 801 public static LongStream generate(LongSupplier s) { 802 Objects.requireNonNull(s); 803 return StreamSupport.longStream( 804 new StreamSpliterators.InfiniteSupplyingSpliterator.OfLong(Long.MAX_VALUE, s), false); 805 } 806 807 /** 808 * Returns a sequential ordered {@code LongStream} from {@code startInclusive} 809 * (inclusive) to {@code endExclusive} (exclusive) by an incremental step of 810 * {@code 1}. 811 * 812 * @apiNote 813 * <p>An equivalent sequence of increasing values can be produced 814 * sequentially using a {@code for} loop as follows: 815 * <pre>{@code 816 * for (long i = startInclusive; i < endExclusive ; i++) { ... } 817 * }</pre> 818 * 819 * @param startInclusive the (inclusive) initial value 820 * @param endExclusive the exclusive upper bound 821 * @return a sequential {@code LongStream} for the range of {@code long} 822 * elements 823 */ 824 public static LongStream range(long startInclusive, final long endExclusive) { 825 if (startInclusive >= endExclusive) { 826 return empty(); 827 } else if (endExclusive - startInclusive < 0) { 828 // Size of range > Long.MAX_VALUE 829 // Split the range in two and concatenate 830 // Note: if the range is [Long.MIN_VALUE, Long.MAX_VALUE) then 831 // the lower range, [Long.MIN_VALUE, 0) will be further split in two 832 long m = startInclusive + Long.divideUnsigned(endExclusive - startInclusive, 2) + 1; 833 return concat(range(startInclusive, m), range(m, endExclusive)); 834 } else { 835 return StreamSupport.longStream( 836 new Streams.RangeLongSpliterator(startInclusive, endExclusive, false), false); 837 } 838 } 839 840 /** 841 * Returns a sequential ordered {@code LongStream} from {@code startInclusive} 842 * (inclusive) to {@code endInclusive} (inclusive) by an incremental step of 843 * {@code 1}. 844 * 845 * @apiNote 846 * <p>An equivalent sequence of increasing values can be produced 847 * sequentially using a {@code for} loop as follows: 848 * <pre>{@code 849 * for (long i = startInclusive; i <= endInclusive ; i++) { ... } 850 * }</pre> 851 * 852 * @param startInclusive the (inclusive) initial value 853 * @param endInclusive the inclusive upper bound 854 * @return a sequential {@code LongStream} for the range of {@code long} 855 * elements 856 */ 857 public static LongStream rangeClosed(long startInclusive, final long endInclusive) { 858 if (startInclusive > endInclusive) { 859 return empty(); 860 } else if (endInclusive - startInclusive + 1 <= 0) { 861 // Size of range > Long.MAX_VALUE 862 // Split the range in two and concatenate 863 // Note: if the range is [Long.MIN_VALUE, Long.MAX_VALUE] then 864 // the lower range, [Long.MIN_VALUE, 0), and upper range, 865 // [0, Long.MAX_VALUE], will both be further split in two 866 long m = startInclusive + Long.divideUnsigned(endInclusive - startInclusive, 2) + 1; 867 return concat(range(startInclusive, m), rangeClosed(m, endInclusive)); 868 } else { 869 return StreamSupport.longStream( 870 new Streams.RangeLongSpliterator(startInclusive, endInclusive, true), false); 871 } 872 } 873 874 /** 875 * Creates a lazily concatenated stream whose elements are all the 876 * elements of the first stream followed by all the elements of the 877 * second stream. The resulting stream is ordered if both 878 * of the input streams are ordered, and parallel if either of the input 879 * streams is parallel. When the resulting stream is closed, the close 880 * handlers for both input streams are invoked. 881 * 882 * @param a the first stream 883 * @param b the second stream 884 * @return the concatenation of the two input streams 885 */ 886 public static LongStream concat(LongStream a, LongStream b) { 887 Objects.requireNonNull(a); 888 Objects.requireNonNull(b); 889 890 Spliterator.OfLong split = new Streams.ConcatSpliterator.OfLong( 891 a.spliterator(), b.spliterator()); 892 LongStream stream = StreamSupport.longStream(split, a.isParallel() || b.isParallel()); 893 return stream.onClose(Streams.composedClose(a, b)); 894 } 895 896 /** 897 * A mutable builder for a {@code LongStream}. 898 * 899 * <p>A stream builder has a lifecycle, which starts in a building 900 * phase, during which elements can be added, and then transitions to a built 901 * phase, after which elements may not be added. The built phase begins 902 * begins when the {@link #build()} method is called, which creates an 903 * ordered stream whose elements are the elements that were added to the 904 * stream builder, in the order they were added. 905 * 906 * @see LongStream#builder() 907 * @since 1.8 908 */ 909 public interface Builder extends LongConsumer { 910 911 /** 912 * Adds an element to the stream being built. 913 * 914 * @throws IllegalStateException if the builder has already transitioned 915 * to the built state 916 */ 917 @Override 918 void accept(long t); 919 920 /** 921 * Adds an element to the stream being built. 922 * 923 * @implSpec 924 * The default implementation behaves as if: 925 * <pre>{@code 926 * accept(t) 927 * return this; 928 * }</pre> 929 * 930 * @param t the element to add 931 * @return {@code this} builder 932 * @throws IllegalStateException if the builder has already transitioned 933 * to the built state 934 */ 935 default Builder add(long t) { 936 accept(t); 937 return this; 938 } 939 940 /** 941 * Builds the stream, transitioning this builder to the built state. 942 * An {@code IllegalStateException} is thrown if there are further 943 * attempts to operate on the builder after it has entered the built 944 * state. 945 * 946 * @return the built stream 947 * @throws IllegalStateException if the builder has already transitioned 948 * to the built state 949 */ 950 LongStream build(); 951 } 952 }