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.util.Arrays; 28 import java.util.LongSummaryStatistics; 29 import java.util.Objects; 30 import java.util.OptionalDouble; 31 import java.util.OptionalLong; 32 import java.util.PrimitiveIterator; 33 import java.util.Spliterator; 34 import java.util.Spliterators; 35 import java.util.function.BiConsumer; 36 import java.util.function.Function; 37 import java.util.function.LongBinaryOperator; 38 import java.util.function.LongConsumer; 39 import java.util.function.LongFunction; 40 import java.util.function.LongPredicate; 41 import java.util.function.LongSupplier; 42 import java.util.function.LongToDoubleFunction; 43 import java.util.function.LongToIntFunction; 44 import java.util.function.LongUnaryOperator; 45 import java.util.function.ObjLongConsumer; 46 import java.util.function.Supplier; 47 48 /** 49 * A sequence of primitive long elements supporting sequential and parallel 50 * bulk operations. Streams support lazy intermediate operations (transforming 51 * a stream to another stream) such as {@code filter} and {@code map}, and terminal 52 * operations (consuming the contents of a stream to produce a result or 53 * side-effect), such as {@code forEach}, {@code findFirst}, and {@code 54 * iterator}. Once an operation has been performed on a stream, it 55 * is considered <em>consumed</em> and no longer usable for other operations. 56 * 57 * <p>For sequential stream pipelines, all operations are performed in the 58 * <a href="package-summary.html#Ordering">encounter order</a> of the pipeline 59 * source, if the pipeline source has a defined encounter order. 60 * 61 * <p>For parallel stream pipelines, unless otherwise specified, intermediate 62 * stream operations preserve the <a href="package-summary.html#Ordering"> 63 * encounter order</a> of their source, and terminal operations 64 * respect the encounter order of their source, if the source 65 * has an encounter order. Provided that and parameters to stream operations 66 * satisfy the <a href="package-summary.html#NonInterference">non-interference 67 * requirements</a>, and excepting differences arising from the absence of 68 * a defined encounter order, the result of a stream pipeline should be the 69 * stable across multiple executions of the same operations on the same source. 70 * However, the timing and thread in which side-effects occur (for those 71 * operations which are allowed to produce side-effects, such as 72 * {@link #forEach(LongConsumer)}), are explicitly nondeterministic for parallel 73 * execution of stream pipelines. 74 * 75 * <p>Unless otherwise noted, passing a {@code null} argument to any stream 76 * method may result in a {@link NullPointerException}. 77 * 78 * @apiNote 79 * Streams are not data structures; they do not manage the storage for their 80 * elements, nor do they support access to individual elements. However, 81 * you can use the {@link #iterator()} or {@link #spliterator()} operations to 82 * perform a controlled traversal. 83 * 84 * @since 1.8 85 * @see <a href="package-summary.html">java.util.stream</a> 86 */ 87 public interface LongStream extends BaseStream<Long, LongStream> { 88 89 /** 90 * Returns a stream consisting of the elements of this stream that match 91 * the given predicate. 92 * 93 * <p>This is an <a href="package-summary.html#StreamOps">intermediate 94 * operation</a>. 95 * 96 * @param predicate a <a href="package-summary.html#NonInterference"> 97 * non-interfering, stateless</a> predicate to apply to 98 * each element to determine if it should be included 99 * @return the new stream 100 */ 101 LongStream filter(LongPredicate predicate); 102 103 /** 104 * Returns a stream consisting of the results of applying the given 105 * function to the elements of this stream. 106 * 107 * <p>This is an <a href="package-summary.html#StreamOps">intermediate 108 * operation</a>. 109 * 110 * @param mapper a <a href="package-summary.html#NonInterference"> 111 * non-interfering, stateless</a> function to apply to each 112 * element 113 * @return the new stream 114 */ 115 LongStream map(LongUnaryOperator mapper); 116 117 /** 118 * Returns an object-valued {@code Stream} consisting of the results of 119 * applying the given function to the elements of this stream. 120 * 121 * <p>This is an <a href="package-summary.html#StreamOps"> 122 * intermediate operation</a>. 123 * 124 * @param <U> the element type of the new stream 125 * @param mapper a <a href="package-summary.html#NonInterference"> 126 * non-interfering, stateless</a> function to apply to each 127 * element 128 * @return the new stream 129 */ 130 <U> Stream<U> mapToObj(LongFunction<? extends U> mapper); 131 132 /** 133 * Returns an {@code IntStream} consisting of the results of applying the 134 * given function to the elements of this stream. 135 * 136 * <p>This is an <a href="package-summary.html#StreamOps">intermediate 137 * operation</a>. 138 * 139 * @param mapper a <a href="package-summary.html#NonInterference"> 140 * non-interfering, stateless</a> function to apply to each 141 * element 142 * @return the new stream 143 */ 144 IntStream mapToInt(LongToIntFunction mapper); 145 146 /** 147 * Returns a {@code DoubleStream} consisting of the results of applying the 148 * given function to the elements of this stream. 149 * 150 * <p>This is an <a href="package-summary.html#StreamOps">intermediate 151 * operation</a>. 152 * 153 * @param mapper a <a href="package-summary.html#NonInterference"> 154 * non-interfering, stateless</a> function to apply to each 155 * element 156 * @return the new stream 157 */ 158 DoubleStream mapToDouble(LongToDoubleFunction mapper); 159 160 /** 161 * Returns a stream consisting of the results of replacing each element of 162 * this stream with the contents of the stream produced by applying the 163 * provided mapping function to each element. 164 * 165 * <p>This is an <a href="package-summary.html#StreamOps">intermediate 166 * operation</a>. 167 * 168 * @apiNote 169 * The {@code flatMap()} operation has the effect of applying a one-to-many 170 * tranformation to the elements of the stream, and then flattening the 171 * resulting elements into a new stream. For example, if {@code orders} 172 * is a stream of purchase orders, and each purchase order contains a 173 * collection of line items, then the following produces a stream of line 174 * items: 175 * <pre>{@code 176 * orderStream.flatMap(order -> order.getLineItems().stream())... 177 * }</pre> 178 * 179 * @param mapper a <a href="package-summary.html#NonInterference"> 180 * non-interfering, stateless</a> function to apply to 181 * each element which produces an {@code LongStream} of new 182 * values 183 * @return the new stream 184 * @see Stream#flatMap(Function) 185 */ 186 LongStream flatMap(LongFunction<? extends LongStream> mapper); 187 188 /** 189 * Returns a stream consisting of the distinct elements of this stream. 190 * 191 * <p>This is a <a href="package-summary.html#StreamOps">stateful 192 * intermediate operation</a>. 193 * 194 * @return the new stream 195 */ 196 LongStream distinct(); 197 198 /** 199 * Returns a stream consisting of the elements of this stream in sorted 200 * order. 201 * 202 * <p>This is a <a href="package-summary.html#StreamOps">stateful 203 * intermediate operation</a>. 204 * 205 * @return the new stream 206 */ 207 LongStream sorted(); 208 209 /** 210 * Returns a stream consisting of the elements of this stream, additionally 211 * performing the provided action on each element as elements are consumed 212 * from the resulting stream. 213 * 214 * <p>This is an <a href="package-summary.html#StreamOps">intermediate 215 * operation</a>. 216 * 217 * <p>For parallel stream pipelines, the action may be called at 218 * whatever time and in whatever thread the element is made available by the 219 * upstream operation. If the action modifies shared state, 220 * it is responsible for providing the required synchronization. 221 * 222 * @apiNote This method exists mainly to support debugging, where you want 223 * to see the elements as they flow past a certain point in a pipeline: 224 * <pre>{@code 225 * list.stream() 226 * .filter(filteringFunction) 227 * .peek(e -> {System.out.println("Filtered value: " + e); }); 228 * .map(mappingFunction) 229 * .peek(e -> {System.out.println("Mapped value: " + e); }); 230 * .collect(Collectors.toLongSummaryStastistics()); 231 * }</pre> 232 * 233 * @param consumer a <a href="package-summary.html#NonInterference"> 234 * non-interfering</a> action to perform on the elements as 235 * they are consumed from the stream 236 * @return the new stream 237 */ 238 LongStream peek(LongConsumer consumer); 239 240 /** 241 * Returns a stream consisting of the elements of this stream, truncated 242 * to be no longer than {@code maxSize} in length. 243 * 244 * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting 245 * stateful intermediate operation</a>. 246 * 247 * @param maxSize the number of elements the stream should be limited to 248 * @return the new stream 249 * @throws IllegalArgumentException if {@code maxSize} is negative 250 */ 251 LongStream limit(long maxSize); 252 253 /** 254 * Returns a stream consisting of the remaining elements of this stream 255 * after indexing {@code startInclusive} elements into the stream. If the 256 * {@code startInclusive} index lies past the end of this stream then an 257 * empty stream will be returned. 258 * 259 * <p>This is a <a href="package-summary.html#StreamOps">stateful 260 * intermediate operation</a>. 261 * 262 * @param startInclusive the number of leading elements to skip 263 * @return the new stream 264 * @throws IllegalArgumentException if {@code startInclusive} is negative 265 */ 266 LongStream substream(long startInclusive); 267 268 /** 269 * Returns a stream consisting of the remaining elements of this stream 270 * after indexing {@code startInclusive} elements into the stream and 271 * truncated to contain no more than {@code endExclusive - startInclusive} 272 * elements. If the {@code startInclusive} index lies past the end 273 * of this stream then an empty stream will be returned. 274 * 275 * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting 276 * stateful intermediate operation</a>. 277 * 278 * @param startInclusive the starting position of the substream, inclusive 279 * @param endExclusive the ending position of the substream, exclusive 280 * @return the new stream 281 * @throws IllegalArgumentException if {@code startInclusive} or 282 * {@code endExclusive} is negative or {@code startInclusive} is greater 283 * than {@code endExclusive} 284 */ 285 LongStream substream(long startInclusive, long endExclusive); 286 287 /** 288 * Performs an action for each element of this stream. 289 * 290 * <p>This is a <a href="package-summary.html#StreamOps">terminal 291 * operation</a>. 292 * 293 * <p>For parallel stream pipelines, this operation does <em>not</em> 294 * guarantee to respect the encounter order of the stream, as doing so 295 * would sacrifice the benefit of parallelism. For any given element, the 296 * action may be performed at whatever time and in whatever thread the 297 * library chooses. If the action accesses shared state, it is 298 * responsible for providing the required synchronization. 299 * 300 * @param action a <a href="package-summary.html#NonInterference"> 301 * non-interfering</a> action to perform on the elements 302 */ 303 void forEach(LongConsumer action); 304 305 /** 306 * Performs an action for each element of this stream, guaranteeing that 307 * each element is processed in encounter order for streams that have a 308 * defined encounter order. 309 * 310 * <p>This is a <a href="package-summary.html#StreamOps">terminal 311 * operation</a>. 312 * 313 * @param action a <a href="package-summary.html#NonInterference"> 314 * non-interfering</a> action to perform on the elements 315 * @see #forEach(LongConsumer) 316 */ 317 void forEachOrdered(LongConsumer action); 318 319 /** 320 * Returns an array containing the elements of this stream. 321 * 322 * <p>This is a <a href="package-summary.html#StreamOps">terminal 323 * operation</a>. 324 * 325 * @return an array containing the elements of this stream 326 */ 327 long[] toArray(); 328 329 /** 330 * Performs a <a href="package-summary.html#Reduction">reduction</a> on the 331 * elements of this stream, using the provided identity value and an 332 * <a href="package-summary.html#Associativity">associative</a> 333 * accumulation function, and returns the reduced value. This is equivalent 334 * to: 335 * <pre>{@code 336 * long result = identity; 337 * for (long element : this stream) 338 * result = accumulator.apply(result, element) 339 * return result; 340 * }</pre> 341 * 342 * but is not constrained to execute sequentially. 343 * 344 * <p>The {@code identity} value must be an identity for the accumulator 345 * function. This means that for all {@code x}, 346 * {@code accumulator.apply(identity, x)} is equal to {@code x}. 347 * The {@code accumulator} function must be an 348 * <a href="package-summary.html#Associativity">associative</a> function. 349 * 350 * <p>This is a <a href="package-summary.html#StreamOps">terminal 351 * operation</a>. 352 * 353 * @apiNote Sum, min, max, and average are all special cases of reduction. 354 * Summing a stream of numbers can be expressed as: 355 * 356 * <pre>{@code 357 * long sum = integers.reduce(0, (a, b) -> a+b); 358 * }</pre> 359 * 360 * or more compactly: 361 * 362 * <pre>{@code 363 * long sum = integers.reduce(0, Long::sum); 364 * }</pre> 365 * 366 * <p>While this may seem a more roundabout way to perform an aggregation 367 * compared to simply mutating a running total in a loop, reduction 368 * operations parallelize more gracefully, without needing additional 369 * synchronization and with greatly reduced risk of data races. 370 * 371 * @param identity the identity value for the accumulating function 372 * @param op an <a href="package-summary.html#Associativity">associative</a> 373 * <a href="package-summary.html#NonInterference">non-interfering, 374 * stateless</a> function for combining two values 375 * @return the result of the reduction 376 * @see #sum() 377 * @see #min() 378 * @see #max() 379 * @see #average() 380 */ 381 long reduce(long identity, LongBinaryOperator op); 382 383 /** 384 * Performs a <a href="package-summary.html#Reduction">reduction</a> on the 385 * elements of this stream, using an 386 * <a href="package-summary.html#Associativity">associative</a> accumulation 387 * function, and returns an {@code OptionalLong} describing the reduced value, 388 * if any. This is equivalent to: 389 * <pre>{@code 390 * boolean foundAny = false; 391 * long result = null; 392 * for (long element : this stream) { 393 * if (!foundAny) { 394 * foundAny = true; 395 * result = element; 396 * } 397 * else 398 * result = accumulator.apply(result, element); 399 * } 400 * return foundAny ? OptionalLong.of(result) : OptionalLong.empty(); 401 * }</pre> 402 * 403 * but is not constrained to execute sequentially. 404 * 405 * <p>The {@code accumulator} function must be an 406 * <a href="package-summary.html#Associativity">associative</a> function. 407 * 408 * <p>This is a <a href="package-summary.html#StreamOps">terminal 409 * operation</a>. 410 * 411 * @param op an <a href="package-summary.html#Associativity">associative</a> 412 * <a href="package-summary.html#NonInterference">non-interfering, 413 * stateless</a> function for combining two values 414 * @return the result of the reduction 415 * @see #reduce(long, LongBinaryOperator) 416 */ 417 OptionalLong reduce(LongBinaryOperator op); 418 419 /** 420 * Performs a <a href="package-summary.html#MutableReduction">mutable 421 * reduction</a> operation on the elements of this stream. A mutable 422 * reduction is one in which the reduced value is a mutable value holder, 423 * such as an {@code ArrayList}, and elements are incorporated by updating 424 * the state of the result, rather than by replacing the result. This 425 * produces a result equivalent to: 426 * <pre>{@code 427 * R result = resultFactory.get(); 428 * for (long element : this stream) 429 * accumulator.accept(result, element); 430 * return result; 431 * }</pre> 432 * 433 * <p>Like {@link #reduce(long, LongBinaryOperator)}, {@code collect} operations 434 * can be parallelized without requiring additional synchronization. 435 * 436 * <p>This is a <a href="package-summary.html#StreamOps">terminal 437 * operation</a>. 438 * 439 * @param <R> type of the result 440 * @param resultFactory a function that creates a new result container. 441 * For a parallel execution, this function may be 442 * called multiple times and must return a fresh value 443 * each time. 444 * @param accumulator an <a href="package-summary.html#Associativity">associative</a> 445 * <a href="package-summary.html#NonInterference">non-interfering, 446 * stateless</a> function for incorporating an additional 447 * element into a result 448 * @param combiner an <a href="package-summary.html#Associativity">associative</a> 449 * <a href="package-summary.html#NonInterference">non-interfering, 450 * stateless</a> function for combining two values, which 451 * must be compatible with the accumulator function 452 * @return the result of the reduction 453 * @see Stream#collect(Supplier, BiConsumer, BiConsumer) 454 */ 455 <R> R collect(Supplier<R> resultFactory, 456 ObjLongConsumer<R> accumulator, 457 BiConsumer<R, R> combiner); 458 459 /** 460 * Returns the sum of elements in this stream. This is a special case 461 * of a <a href="package-summary.html#MutableReduction">reduction</a> 462 * and is equivalent to: 463 * <pre>{@code 464 * return reduce(0, Long::sum); 465 * }</pre> 466 * 467 * @return the sum of elements in this stream 468 */ 469 long sum(); 470 471 /** 472 * Returns an {@code OptionalLong} describing the minimum element of this 473 * stream, or an empty optional if this stream is empty. This is a special 474 * case of a <a href="package-summary.html#MutableReduction">reduction</a> 475 * and is equivalent to: 476 * <pre>{@code 477 * return reduce(Long::min); 478 * }</pre> 479 * 480 * <p>This is a <a href="package-summary.html#StreamOps">terminal operation</a>. 481 * 482 483 * @return an {@code OptionalLong} containing the minimum element of this 484 * stream, or an empty {@code OptionalLong} if the stream is empty 485 */ 486 OptionalLong min(); 487 488 /** 489 * Returns an {@code OptionalLong} describing the maximum element of this 490 * stream, or an empty optional if this stream is empty. This is a special 491 * case of a <a href="package-summary.html#MutableReduction">reduction</a> 492 * and is equivalent to: 493 * <pre>{@code 494 * return reduce(Long::max); 495 * }</pre> 496 * 497 * <p>This is a <a href="package-summary.html#StreamOps">terminal 498 * operation</a>. 499 * 500 * @return an {@code OptionalLong} containing the maximum element of this 501 * stream, or an empty {@code OptionalLong} if the stream is empty 502 */ 503 OptionalLong max(); 504 505 /** 506 * Returns the count of elements in this stream. This is a special case of 507 * a <a href="package-summary.html#MutableReduction">reduction</a> and is 508 * equivalent to: 509 * <pre>{@code 510 * return map(e -> 1L).sum(); 511 * }</pre> 512 * 513 * <p>This is a <a href="package-summary.html#StreamOps">terminal operation</a>. 514 * 515 * @return the count of elements in this stream 516 */ 517 long count(); 518 519 /** 520 * Returns an {@code OptionalDouble} describing the average of elements of 521 * this stream, or an empty optional if this stream is empty. This is a 522 * special case of a 523 * <a href="package-summary.html#MutableReduction">reduction</a>. 524 * 525 * @return an {@code OptionalDouble} containing the average element of this 526 * stream, or an empty optional if the stream is empty 527 */ 528 OptionalDouble average(); 529 530 /** 531 * Returns a {@code LongSummaryStatistics} describing various summary data 532 * about the elements of this stream. This is a special case of a 533 * <a href="package-summary.html#MutableReduction">reduction</a>. 534 * 535 * @return a {@code LongSummaryStatistics} describing various summary data 536 * about the elements of this stream 537 */ 538 LongSummaryStatistics summaryStatistics(); 539 540 /** 541 * Returns whether any elements of this stream match the provided 542 * predicate. May not evaluate the predicate on all elements if not 543 * necessary for determining the result. 544 * 545 * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting 546 * terminal operation</a>. 547 * 548 * @param predicate a <a href="package-summary.html#NonInterference">non-interfering, 549 * stateless</a> predicate to apply to elements of this 550 * stream 551 * @return {@code true} if any elements of the stream match the provided 552 * predicate otherwise {@code false} 553 */ 554 boolean anyMatch(LongPredicate predicate); 555 556 /** 557 * Returns whether all elements of this stream match the provided predicate. 558 * May not evaluate the predicate on all elements if not necessary for 559 * determining the result. 560 * 561 * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting 562 * terminal operation</a>. 563 * 564 * @param predicate a <a href="package-summary.html#NonInterference">non-interfering, 565 * stateless</a> predicate to apply to elements of this 566 * stream 567 * @return {@code true} if all elements of the stream match the provided 568 * predicate otherwise {@code false} 569 */ 570 boolean allMatch(LongPredicate predicate); 571 572 /** 573 * Returns whether no elements of this stream match the provided predicate. 574 * May not evaluate the predicate on all elements if not necessary for 575 * determining the result. 576 * 577 * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting 578 * terminal operation</a>. 579 * 580 * @param predicate a <a href="package-summary.html#NonInterference">non-interfering, 581 * stateless</a> predicate to apply to elements of this 582 * stream 583 * @return {@code true} if no elements of the stream match the provided 584 * predicate otherwise {@code false} 585 */ 586 boolean noneMatch(LongPredicate predicate); 587 588 /** 589 * Returns an {@link OptionalLong} describing the first element of this 590 * stream (in the encounter order), or an empty {@code OptionalLong} if the 591 * stream is empty. If the stream has no encounter order, then any element 592 * may be returned. 593 * 594 * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting 595 * terminal operation</a>. 596 * 597 * @return an {@code OptionalLong} describing the first element of this 598 * stream, or an empty {@code OptionalLong} if the stream is empty 599 */ 600 OptionalLong findFirst(); 601 602 /** 603 * Returns an {@link OptionalLong} describing some element of the stream, or 604 * an empty {@code OptionalLong} if the stream is empty. 605 * 606 * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting 607 * terminal operation</a>. 608 * 609 * <p>The behavior of this operation is explicitly nondeterministic; it is 610 * free to select any element in the stream. This is to allow for maximal 611 * performance in parallel operations; the cost is that multiple invocations 612 * on the same source may not return the same result. (If the first element 613 * in the encounter order is desired, use {@link #findFirst()} instead.) 614 * 615 * @return an {@code OptionalLong} describing some element of this stream, 616 * or an empty {@code OptionalLong} if the stream is empty 617 * @see #findFirst() 618 */ 619 OptionalLong findAny(); 620 621 /** 622 * Returns a {@code DoubleStream} consisting of the elements of this stream, 623 * converted to {@code double}. 624 * 625 * @return a {@code DoubleStream} consisting of the elements of this stream, 626 * converted to {@code double} 627 */ 628 DoubleStream asDoubleStream(); 629 630 /** 631 * Returns a {@code Stream} consisting of the elements of this stream, 632 * each boxed to a {@code Long}. 633 * 634 * @return a {@code Stream} consistent of the elements of this stream, 635 * each boxed to {@code Long} 636 */ 637 Stream<Long> boxed(); 638 639 @Override 640 LongStream sequential(); 641 642 @Override 643 LongStream parallel(); 644 645 @Override 646 PrimitiveIterator.OfLong iterator(); 647 648 @Override 649 Spliterator.OfLong spliterator(); 650 651 // Static factories 652 653 /** 654 * Returns a builder for a {@code LongStream}. 655 * 656 * @return a stream builder 657 */ 658 public static StreamBuilder.OfLong builder() { 659 return new Streams.LongStreamBuilderImpl(); 660 } 661 662 /** 663 * Returns an empty sequential {@code LongStream}. 664 * 665 * @return an empty sequential stream 666 */ 667 public static LongStream empty() { 668 return StreamSupport.longStream(Spliterators.emptyLongSpliterator()); 669 } 670 671 /** 672 * Returns a sequential {@code LongStream} containing a single element. 673 * 674 * @param t the single element 675 * @return a singleton sequential stream 676 */ 677 public static LongStream of(long t) { 678 return StreamSupport.longStream(new Streams.LongStreamBuilderImpl(t)); 679 } 680 681 /** 682 * Returns a sequential stream whose elements are the specified values. 683 * 684 * @param values the elements of the new stream 685 * @return the new stream 686 */ 687 public static LongStream of(long... values) { 688 return Arrays.stream(values); 689 } 690 691 /** 692 * Returns an infinite sequential {@code LongStream} produced by iterative 693 * application of a function {@code f} to an initial element {@code seed}, 694 * producing a {@code Stream} consisting of {@code seed}, {@code f(seed)}, 695 * {@code f(f(seed))}, etc. 696 * 697 * <p>The first element (position {@code 0}) in the {@code LongStream} will 698 * be the provided {@code seed}. For {@code n > 0}, the element at position 699 * {@code n}, will be the result of applying the function {@code f} to the 700 * element at position {@code n - 1}. 701 * 702 * @param seed the initial element 703 * @param f a function to be applied to to the previous element to produce 704 * a new element 705 * @return a new sequential {@code LongStream} 706 */ 707 public static LongStream iterate(final long seed, final LongUnaryOperator f) { 708 Objects.requireNonNull(f); 709 final PrimitiveIterator.OfLong iterator = new PrimitiveIterator.OfLong() { 710 long t = seed; 711 712 @Override 713 public boolean hasNext() { 714 return true; 715 } 716 717 @Override 718 public long nextLong() { 719 long v = t; 720 t = f.applyAsLong(t); 721 return v; 722 } 723 }; 724 return StreamSupport.longStream(Spliterators.spliteratorUnknownSize( 725 iterator, 726 Spliterator.ORDERED | Spliterator.IMMUTABLE | Spliterator.NONNULL)); 727 } 728 729 /** 730 * Returns a sequential {@code LongStream} where each element is generated 731 * by a {@code LongSupplier}. This is suitable for generating constant 732 * streams, streams of random elements, etc. 733 * 734 * @param s the {@code LongSupplier} for generated elements 735 * @return a new sequential {@code LongStream} 736 */ 737 public static LongStream generate(LongSupplier s) { 738 Objects.requireNonNull(s); 739 return StreamSupport.longStream( 740 new StreamSpliterators.InfiniteSupplyingSpliterator.OfLong(Long.MAX_VALUE, s)); 741 } 742 743 /** 744 * Returns a sequential {@code LongStream} from {@code startInclusive} 745 * (inclusive) to {@code endExclusive} (exclusive) by an incremental step of 746 * {@code 1}. 747 * 748 * @apiNote 749 * <p>An equivalent sequence of increasing values can be produced 750 * sequentially using a {@code for} loop as follows: 751 * <pre>{@code 752 * for (long i = startInclusive; i < endExclusive ; i++) { ... } 753 * }</pre> 754 * 755 * @param startInclusive the (inclusive) initial value 756 * @param endExclusive the exclusive upper bound 757 * @return a sequential {@code LongStream} for the range of {@code long} 758 * elements 759 */ 760 public static LongStream range(long startInclusive, final long endExclusive) { 761 if (startInclusive >= endExclusive) { 762 return empty(); 763 } else if (endExclusive - startInclusive < 0) { 764 // Size of range > Long.MAX_VALUE 765 // Split the range in two and concatenate 766 // Note: if the range is [Long.MIN_VALUE, Long.MAX_VALUE) then 767 // the lower range, [Long.MIN_VALUE, 0) will be further split in two 768 long m = startInclusive + Long.divideUnsigned(endExclusive - startInclusive, 2) + 1; 769 return concat(range(startInclusive, m), range(m, endExclusive)); 770 } else { 771 return StreamSupport.longStream( 772 new Streams.RangeLongSpliterator(startInclusive, endExclusive, false)); 773 } 774 } 775 776 /** 777 * Returns a sequential {@code LongStream} from {@code startInclusive} 778 * (inclusive) to {@code endInclusive} (inclusive) by an incremental step of 779 * {@code 1}. 780 * 781 * @apiNote 782 * <p>An equivalent sequence of increasing values can be produced 783 * sequentially using a {@code for} loop as follows: 784 * <pre>{@code 785 * for (long i = startInclusive; i <= endInclusive ; i++) { ... } 786 * }</pre> 787 * 788 * @param startInclusive the (inclusive) initial value 789 * @param endInclusive the inclusive upper bound 790 * @return a sequential {@code LongStream} for the range of {@code long} 791 * elements 792 */ 793 public static LongStream rangeClosed(long startInclusive, final long endInclusive) { 794 if (startInclusive > endInclusive) { 795 return empty(); 796 } else if (endInclusive - startInclusive + 1 <= 0) { 797 // Size of range > Long.MAX_VALUE 798 // Split the range in two and concatenate 799 // Note: if the range is [Long.MIN_VALUE, Long.MAX_VALUE] then 800 // the lower range, [Long.MIN_VALUE, 0), and upper range, 801 // [0, Long.MAX_VALUE], will both be further split in two 802 long m = startInclusive + Long.divideUnsigned(endInclusive - startInclusive, 2) + 1; 803 return concat(range(startInclusive, m), rangeClosed(m, endInclusive)); 804 } else { 805 return StreamSupport.longStream( 806 new Streams.RangeLongSpliterator(startInclusive, endInclusive, true)); 807 } 808 } 809 810 /** 811 * Creates a lazy concatenated {@code LongStream} whose elements are all the 812 * elements of a first {@code LongStream} succeeded by all the elements of the 813 * second {@code LongStream}. The resulting stream is ordered if both 814 * of the input streams are ordered, and parallel if either of the input 815 * streams is parallel. 816 * 817 * @param a the first stream 818 * @param b the second stream to concatenate on to end of the first stream 819 * @return the concatenation of the two streams 820 */ 821 public static LongStream concat(LongStream a, LongStream b) { 822 Objects.requireNonNull(a); 823 Objects.requireNonNull(b); 824 825 Spliterator.OfLong split = new Streams.ConcatSpliterator.OfLong( 826 a.spliterator(), b.spliterator()); 827 return (a.isParallel() || b.isParallel()) 828 ? StreamSupport.longParallelStream(split) 829 : StreamSupport.longStream(split); 830 } 831 }