1 /* 2 * Copyright (c) 2013, 2015, 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-valued elements supporting sequential and parallel 50 * aggregate operations. This is the {@code long} primitive specialization of 51 * {@link Stream}. 52 * 53 * <p>The following example illustrates an aggregate operation using 54 * {@link Stream} and {@link LongStream}, computing the sum of the weights of the 55 * red widgets: 56 * 57 * <pre>{@code 58 * long sum = widgets.stream() 59 * .filter(w -> w.getColor() == RED) 60 * .mapToLong(w -> w.getWeight()) 61 * .sum(); 62 * }</pre> 63 * 64 * See the class documentation for {@link Stream} and the package documentation 65 * for <a href="package-summary.html">java.util.stream</a> for additional 66 * specification of streams, stream operations, stream pipelines, and 67 * parallelism. 68 * 69 * @since 1.8 70 * @see Stream 71 * @see <a href="package-summary.html">java.util.stream</a> 72 */ 73 public interface LongStream extends BaseStream<Long, LongStream> { 74 75 /** 76 * Returns a stream consisting of the elements of this stream that match 77 * the given predicate. 78 * 79 * <p>This is an <a href="package-summary.html#StreamOps">intermediate 80 * operation</a>. 81 * 82 * @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>, 83 * <a href="package-summary.html#Statelessness">stateless</a> 84 * predicate to apply to each element to determine if it 85 * should be included 86 * @return the new stream 87 */ 88 LongStream filter(LongPredicate predicate); 89 90 /** 91 * Returns a stream consisting of the results of applying the given 92 * function to the elements of this stream. 93 * 94 * <p>This is an <a href="package-summary.html#StreamOps">intermediate 95 * operation</a>. 96 * 97 * @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>, 98 * <a href="package-summary.html#Statelessness">stateless</a> 99 * function to apply to each element 100 * @return the new stream 101 */ 102 LongStream map(LongUnaryOperator mapper); 103 104 /** 105 * Returns an object-valued {@code Stream} consisting of the results of 106 * applying the given function to the elements of this stream. 107 * 108 * <p>This is an <a href="package-summary.html#StreamOps"> 109 * intermediate operation</a>. 110 * 111 * @param <U> the element type of the new stream 112 * @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>, 113 * <a href="package-summary.html#Statelessness">stateless</a> 114 * function to apply to each element 115 * @return the new stream 116 */ 117 <U> Stream<U> mapToObj(LongFunction<? extends U> mapper); 118 119 /** 120 * Returns an {@code IntStream} consisting of the results of applying the 121 * given function to the elements of this stream. 122 * 123 * <p>This is an <a href="package-summary.html#StreamOps">intermediate 124 * operation</a>. 125 * 126 * @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>, 127 * <a href="package-summary.html#Statelessness">stateless</a> 128 * function to apply to each element 129 * @return the new stream 130 */ 131 IntStream mapToInt(LongToIntFunction mapper); 132 133 /** 134 * Returns a {@code DoubleStream} consisting of the results of applying the 135 * given function to the elements of this stream. 136 * 137 * <p>This is an <a href="package-summary.html#StreamOps">intermediate 138 * operation</a>. 139 * 140 * @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>, 141 * <a href="package-summary.html#Statelessness">stateless</a> 142 * function to apply to each element 143 * @return the new stream 144 */ 145 DoubleStream mapToDouble(LongToDoubleFunction mapper); 146 147 /** 148 * Returns a stream consisting of the results of replacing each element of 149 * this stream with the contents of a mapped stream produced by applying 150 * the provided mapping function to each element. Each mapped stream is 151 * {@link java.util.stream.BaseStream#close() closed} after its contents 152 * have been placed into this stream. (If a mapped stream is {@code null} 153 * an empty stream is used, instead.) 154 * 155 * <p>This is an <a href="package-summary.html#StreamOps">intermediate 156 * operation</a>. 157 * 158 * @param mapper a <a href="package-summary.html#NonInterference">non-interfering</a>, 159 * <a href="package-summary.html#Statelessness">stateless</a> 160 * function to apply to each element which produces a 161 * {@code LongStream} of new values 162 * @return the new stream 163 * @see Stream#flatMap(Function) 164 */ 165 LongStream flatMap(LongFunction<? extends LongStream> mapper); 166 167 /** 168 * Returns a stream consisting of the distinct elements of this stream. 169 * 170 * <p>This is a <a href="package-summary.html#StreamOps">stateful 171 * intermediate operation</a>. 172 * 173 * @return the new stream 174 */ 175 LongStream distinct(); 176 177 /** 178 * Returns a stream consisting of the elements of this stream in sorted 179 * order. 180 * 181 * <p>This is a <a href="package-summary.html#StreamOps">stateful 182 * intermediate operation</a>. 183 * 184 * @return the new stream 185 */ 186 LongStream sorted(); 187 188 /** 189 * Returns a stream consisting of the elements of this stream, additionally 190 * performing the provided action on each element as elements are consumed 191 * from the resulting stream. 192 * 193 * <p>This is an <a href="package-summary.html#StreamOps">intermediate 194 * operation</a>. 195 * 196 * <p>For parallel stream pipelines, the action may be called at 197 * whatever time and in whatever thread the element is made available by the 198 * upstream operation. If the action modifies shared state, 199 * it is responsible for providing the required synchronization. 200 * 201 * @apiNote This method exists mainly to support debugging, where you want 202 * to see the elements as they flow past a certain point in a pipeline: 203 * <pre>{@code 204 * LongStream.of(1, 2, 3, 4) 205 * .filter(e -> e > 2) 206 * .peek(e -> System.out.println("Filtered value: " + e)) 207 * .map(e -> e * e) 208 * .peek(e -> System.out.println("Mapped value: " + e)) 209 * .sum(); 210 * }</pre> 211 * 212 * @param action a <a href="package-summary.html#NonInterference"> 213 * non-interfering</a> action to perform on the elements as 214 * they are consumed from the stream 215 * @return the new stream 216 */ 217 LongStream peek(LongConsumer action); 218 219 /** 220 * Returns a stream consisting of the elements of this stream, truncated 221 * to be no longer than {@code maxSize} in length. 222 * 223 * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting 224 * stateful intermediate operation</a>. 225 * 226 * @apiNote 227 * While {@code limit()} is generally a cheap operation on sequential 228 * stream pipelines, it can be quite expensive on ordered parallel pipelines, 229 * especially for large values of {@code maxSize}, since {@code limit(n)} 230 * is constrained to return not just any <em>n</em> elements, but the 231 * <em>first n</em> elements in the encounter order. Using an unordered 232 * stream source (such as {@link #generate(LongSupplier)}) or removing the 233 * ordering constraint with {@link #unordered()} may result in significant 234 * speedups of {@code limit()} in parallel pipelines, if the semantics of 235 * your situation permit. If consistency with encounter order is required, 236 * and you are experiencing poor performance or memory utilization with 237 * {@code limit()} in parallel pipelines, switching to sequential execution 238 * with {@link #sequential()} may improve performance. 239 * 240 * @param maxSize the number of elements the stream should be limited to 241 * @return the new stream 242 * @throws IllegalArgumentException if {@code maxSize} is negative 243 */ 244 LongStream limit(long maxSize); 245 246 /** 247 * Returns a stream consisting of the remaining elements of this stream 248 * after discarding the first {@code n} elements of the stream. 249 * If this stream contains fewer than {@code n} elements then an 250 * empty stream will be returned. 251 * 252 * <p>This is a <a href="package-summary.html#StreamOps">stateful 253 * intermediate operation</a>. 254 * 255 * @apiNote 256 * While {@code skip()} is generally a cheap operation on sequential 257 * stream pipelines, it can be quite expensive on ordered parallel pipelines, 258 * especially for large values of {@code n}, since {@code skip(n)} 259 * is constrained to skip not just any <em>n</em> elements, but the 260 * <em>first n</em> elements in the encounter order. Using an unordered 261 * stream source (such as {@link #generate(LongSupplier)}) or removing the 262 * ordering constraint with {@link #unordered()} may result in significant 263 * speedups of {@code skip()} in parallel pipelines, if the semantics of 264 * your situation permit. If consistency with encounter order is required, 265 * and you are experiencing poor performance or memory utilization with 266 * {@code skip()} in parallel pipelines, switching to sequential execution 267 * with {@link #sequential()} may improve performance. 268 * 269 * @param n the number of leading elements to skip 270 * @return the new stream 271 * @throws IllegalArgumentException if {@code n} is negative 272 */ 273 LongStream skip(long n); 274 275 /** 276 * Returns, if this stream is ordered, a stream consisting of the longest 277 * prefix of elements taken from this stream that match the given predicate. 278 * Otherwise returns, if this stream is unordered, a stream consisting of a 279 * subset of elements taken from this stream that match the given predicate. 280 * 281 * <p>If this stream is ordered then the longest prefix is a contiguous 282 * sequence of elements of this stream that match the given predicate. The 283 * first element of the sequence is the first element of this stream, and 284 * the element immediately following the last element of the sequence does 285 * not match the given predicate. 286 * 287 * <p>If this stream is unordered, and some (but not all) elements of this 288 * stream match the given predicate, then the behavior of this operation is 289 * nondeterministic; it is free to take any subset of matching elements 290 * (which includes the empty set). 291 * 292 * <p>Independent of whether this stream is ordered or unordered if all 293 * elements of this stream match the given predicate then this operation 294 * takes all elements (the result is the same as the input), or if no 295 * elements of the stream match the given predicate then no elements are 296 * taken (the result is an empty stream). 297 * 298 * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting 299 * stateful intermediate operation</a>. 300 * 301 * @implSpec 302 * The default implementation obtains the {@link #spliterator() spliterator} 303 * of this stream, wraps that spliterator so as to support the semantics 304 * of this operation on traversal, and returns a new stream associated with 305 * the wrapped spliterator. The returned stream preserves the execution 306 * characteristics of this stream (namely parallel or sequential execution 307 * as per {@link #isParallel()}) but the wrapped spliterator may choose to 308 * not support splitting. When the returned stream is closed, the close 309 * handlers for both the returned and this stream are invoked. 310 * 311 * @apiNote 312 * While {@code takeWhile()} is generally a cheap operation on sequential 313 * stream pipelines, it can be quite expensive on ordered parallel 314 * pipelines, since the operation is constrained to return not just any 315 * valid prefix, but the longest prefix of elements in the encounter order. 316 * Using an unordered stream source (such as 317 * {@link #generate(LongSupplier)}) or removing the ordering constraint with 318 * {@link #unordered()} may result in significant speedups of 319 * {@code takeWhile()} in parallel pipelines, if the semantics of your 320 * situation permit. If consistency with encounter order is required, and 321 * you are experiencing poor performance or memory utilization with 322 * {@code takeWhile()} in parallel pipelines, switching to sequential 323 * execution with {@link #sequential()} may improve performance. 324 * 325 * @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>, 326 * <a href="package-summary.html#Statelessness">stateless</a> 327 * predicate to apply to elements to determine the longest 328 * prefix of elements. 329 * @return the new stream 330 * @since 9 331 */ 332 default LongStream takeWhile(LongPredicate predicate) { 333 Objects.requireNonNull(predicate); 334 // Reuses the unordered spliterator, which, when encounter is present, 335 // is safe to use as long as it configured not to split 336 return StreamSupport.longStream( 337 new WhileOps.UnorderedWhileSpliterator.OfLong.Taking(spliterator(), true, predicate), 338 isParallel()).onClose(this::close); 339 } 340 341 /** 342 * Returns, if this stream is ordered, a stream consisting of the remaining 343 * elements of this stream after dropping the longest prefix of elements 344 * that match the given predicate. Otherwise returns, if this stream is 345 * unordered, a stream consisting of the remaining elements of this stream 346 * after dropping a subset of elements that match the given predicate. 347 * 348 * <p>If this stream is ordered then the longest prefix is a contiguous 349 * sequence of elements of this stream that match the given predicate. The 350 * first element of the sequence is the first element of this stream, and 351 * the element immediately following the last element of the sequence does 352 * not match the given predicate. 353 * 354 * <p>If this stream is unordered, and some (but not all) elements of this 355 * stream match the given predicate, then the behavior of this operation is 356 * nondeterministic; it is free to drop any subset of matching elements 357 * (which includes the empty set). 358 * 359 * <p>Independent of whether this stream is ordered or unordered if all 360 * elements of this stream match the given predicate then this operation 361 * drops all elements (the result is an empty stream), or if no elements of 362 * the stream match the given predicate then no elements are dropped (the 363 * result is the same as the input). 364 * 365 * <p>This is a <a href="package-summary.html#StreamOps">stateful 366 * intermediate operation</a>. 367 * 368 * @implSpec 369 * The default implementation obtains the {@link #spliterator() spliterator} 370 * of this stream, wraps that spliterator so as to support the semantics 371 * of this operation on traversal, and returns a new stream associated with 372 * the wrapped spliterator. The returned stream preserves the execution 373 * characteristics of this stream (namely parallel or sequential execution 374 * as per {@link #isParallel()}) but the wrapped spliterator may choose to 375 * not support splitting. When the returned stream is closed, the close 376 * handlers for both the returned and this stream are invoked. 377 * 378 * @apiNote 379 * While {@code dropWhile()} is generally a cheap operation on sequential 380 * stream pipelines, it can be quite expensive on ordered parallel 381 * pipelines, since the operation is constrained to return not just any 382 * valid prefix, but the longest prefix of elements in the encounter order. 383 * Using an unordered stream source (such as 384 * {@link #generate(LongSupplier)}) or removing the ordering constraint with 385 * {@link #unordered()} may result in significant speedups of 386 * {@code dropWhile()} in parallel pipelines, if the semantics of your 387 * situation permit. If consistency with encounter order is required, and 388 * you are experiencing poor performance or memory utilization with 389 * {@code dropWhile()} in parallel pipelines, switching to sequential 390 * execution with {@link #sequential()} may improve performance. 391 * 392 * @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>, 393 * <a href="package-summary.html#Statelessness">stateless</a> 394 * predicate to apply to elements to determine the longest 395 * prefix of elements. 396 * @return the new stream 397 * @since 9 398 */ 399 default LongStream dropWhile(LongPredicate predicate) { 400 Objects.requireNonNull(predicate); 401 // Reuses the unordered spliterator, which, when encounter is present, 402 // is safe to use as long as it configured not to split 403 return StreamSupport.longStream( 404 new WhileOps.UnorderedWhileSpliterator.OfLong.Dropping(spliterator(), true, predicate), 405 isParallel()).onClose(this::close); 406 } 407 408 /** 409 * Performs an action for each element of this stream. 410 * 411 * <p>This is a <a href="package-summary.html#StreamOps">terminal 412 * operation</a>. 413 * 414 * <p>For parallel stream pipelines, this operation does <em>not</em> 415 * guarantee to respect the encounter order of the stream, as doing so 416 * would sacrifice the benefit of parallelism. For any given element, the 417 * action may be performed at whatever time and in whatever thread the 418 * library chooses. If the action accesses shared state, it is 419 * responsible for providing the required synchronization. 420 * 421 * @param action a <a href="package-summary.html#NonInterference"> 422 * non-interfering</a> action to perform on the elements 423 */ 424 void forEach(LongConsumer action); 425 426 /** 427 * Performs an action for each element of this stream, guaranteeing that 428 * each element is processed in encounter order for streams that have a 429 * defined encounter order. 430 * 431 * <p>This is a <a href="package-summary.html#StreamOps">terminal 432 * operation</a>. 433 * 434 * @param action a <a href="package-summary.html#NonInterference"> 435 * non-interfering</a> action to perform on the elements 436 * @see #forEach(LongConsumer) 437 */ 438 void forEachOrdered(LongConsumer action); 439 440 /** 441 * Returns an array containing the elements of this stream. 442 * 443 * <p>This is a <a href="package-summary.html#StreamOps">terminal 444 * operation</a>. 445 * 446 * @return an array containing the elements of this stream 447 */ 448 long[] toArray(); 449 450 /** 451 * Performs a <a href="package-summary.html#Reduction">reduction</a> on the 452 * elements of this stream, using the provided identity value and an 453 * <a href="package-summary.html#Associativity">associative</a> 454 * accumulation function, and returns the reduced value. This is equivalent 455 * to: 456 * <pre>{@code 457 * long result = identity; 458 * for (long element : this stream) 459 * result = accumulator.applyAsLong(result, element) 460 * return result; 461 * }</pre> 462 * 463 * but is not constrained to execute sequentially. 464 * 465 * <p>The {@code identity} value must be an identity for the accumulator 466 * function. This means that for all {@code x}, 467 * {@code accumulator.apply(identity, x)} is equal to {@code x}. 468 * The {@code accumulator} function must be an 469 * <a href="package-summary.html#Associativity">associative</a> function. 470 * 471 * <p>This is a <a href="package-summary.html#StreamOps">terminal 472 * operation</a>. 473 * 474 * @apiNote Sum, min, max, and average are all special cases of reduction. 475 * Summing a stream of numbers can be expressed as: 476 * 477 * <pre>{@code 478 * long sum = integers.reduce(0, (a, b) -> a+b); 479 * }</pre> 480 * 481 * or more compactly: 482 * 483 * <pre>{@code 484 * long sum = integers.reduce(0, Long::sum); 485 * }</pre> 486 * 487 * <p>While this may seem a more roundabout way to perform an aggregation 488 * compared to simply mutating a running total in a loop, reduction 489 * operations parallelize more gracefully, without needing additional 490 * synchronization and with greatly reduced risk of data races. 491 * 492 * @param identity the identity value for the accumulating function 493 * @param op an <a href="package-summary.html#Associativity">associative</a>, 494 * <a href="package-summary.html#NonInterference">non-interfering</a>, 495 * <a href="package-summary.html#Statelessness">stateless</a> 496 * function for combining two values 497 * @return the result of the reduction 498 * @see #sum() 499 * @see #min() 500 * @see #max() 501 * @see #average() 502 */ 503 long reduce(long identity, LongBinaryOperator op); 504 505 /** 506 * Performs a <a href="package-summary.html#Reduction">reduction</a> on the 507 * elements of this stream, using an 508 * <a href="package-summary.html#Associativity">associative</a> accumulation 509 * function, and returns an {@code OptionalLong} describing the reduced value, 510 * if any. This is equivalent to: 511 * <pre>{@code 512 * boolean foundAny = false; 513 * long result = null; 514 * for (long element : this stream) { 515 * if (!foundAny) { 516 * foundAny = true; 517 * result = element; 518 * } 519 * else 520 * result = accumulator.applyAsLong(result, element); 521 * } 522 * return foundAny ? OptionalLong.of(result) : OptionalLong.empty(); 523 * }</pre> 524 * 525 * but is not constrained to execute sequentially. 526 * 527 * <p>The {@code accumulator} function must be an 528 * <a href="package-summary.html#Associativity">associative</a> function. 529 * 530 * <p>This is a <a href="package-summary.html#StreamOps">terminal 531 * operation</a>. 532 * 533 * @param op an <a href="package-summary.html#Associativity">associative</a>, 534 * <a href="package-summary.html#NonInterference">non-interfering</a>, 535 * <a href="package-summary.html#Statelessness">stateless</a> 536 * function for combining two values 537 * @return the result of the reduction 538 * @see #reduce(long, LongBinaryOperator) 539 */ 540 OptionalLong reduce(LongBinaryOperator op); 541 542 /** 543 * Performs a <a href="package-summary.html#MutableReduction">mutable 544 * reduction</a> operation on the elements of this stream. A mutable 545 * reduction is one in which the reduced value is a mutable result container, 546 * such as an {@code ArrayList}, and elements are incorporated by updating 547 * the state of the result rather than by replacing the result. This 548 * produces a result equivalent to: 549 * <pre>{@code 550 * R result = supplier.get(); 551 * for (long element : this stream) 552 * accumulator.accept(result, element); 553 * return result; 554 * }</pre> 555 * 556 * <p>Like {@link #reduce(long, LongBinaryOperator)}, {@code collect} operations 557 * can be parallelized without requiring additional synchronization. 558 * 559 * <p>This is a <a href="package-summary.html#StreamOps">terminal 560 * operation</a>. 561 * 562 * @param <R> type of the result 563 * @param supplier a function that creates a new result container. For a 564 * parallel execution, this function may be called 565 * multiple times and must return a fresh value each time. 566 * @param accumulator an <a href="package-summary.html#Associativity">associative</a>, 567 * <a href="package-summary.html#NonInterference">non-interfering</a>, 568 * <a href="package-summary.html#Statelessness">stateless</a> 569 * function for incorporating an additional element into a result 570 * @param combiner an <a href="package-summary.html#Associativity">associative</a>, 571 * <a href="package-summary.html#NonInterference">non-interfering</a>, 572 * <a href="package-summary.html#Statelessness">stateless</a> 573 * function for combining two values, which must be 574 * compatible with the accumulator function 575 * @return the result of the reduction 576 * @see Stream#collect(Supplier, BiConsumer, BiConsumer) 577 */ 578 <R> R collect(Supplier<R> supplier, 579 ObjLongConsumer<R> accumulator, 580 BiConsumer<R, R> combiner); 581 582 /** 583 * Returns the sum of elements in this stream. This is a special case 584 * of a <a href="package-summary.html#Reduction">reduction</a> 585 * and is equivalent to: 586 * <pre>{@code 587 * return reduce(0, Long::sum); 588 * }</pre> 589 * 590 * <p>This is a <a href="package-summary.html#StreamOps">terminal 591 * operation</a>. 592 * 593 * @return the sum of elements in this stream 594 */ 595 long sum(); 596 597 /** 598 * Returns an {@code OptionalLong} describing the minimum element of this 599 * stream, or an empty optional if this stream is empty. This is a special 600 * case of a <a href="package-summary.html#Reduction">reduction</a> 601 * and is equivalent to: 602 * <pre>{@code 603 * return reduce(Long::min); 604 * }</pre> 605 * 606 * <p>This is a <a href="package-summary.html#StreamOps">terminal operation</a>. 607 * 608 * @return an {@code OptionalLong} containing the minimum element of this 609 * stream, or an empty {@code OptionalLong} if the stream is empty 610 */ 611 OptionalLong min(); 612 613 /** 614 * Returns an {@code OptionalLong} describing the maximum element of this 615 * stream, or an empty optional if this stream is empty. This is a special 616 * case of a <a href="package-summary.html#Reduction">reduction</a> 617 * and is equivalent to: 618 * <pre>{@code 619 * return reduce(Long::max); 620 * }</pre> 621 * 622 * <p>This is a <a href="package-summary.html#StreamOps">terminal 623 * operation</a>. 624 * 625 * @return an {@code OptionalLong} containing the maximum element of this 626 * stream, or an empty {@code OptionalLong} if the stream is empty 627 */ 628 OptionalLong max(); 629 630 /** 631 * Returns the count of elements in this stream. This is a special case of 632 * a <a href="package-summary.html#Reduction">reduction</a> and is 633 * equivalent to: 634 * <pre>{@code 635 * return map(e -> 1L).sum(); 636 * }</pre> 637 * 638 * <p>This is a <a href="package-summary.html#StreamOps">terminal operation</a>. 639 * 640 * @apiNote 641 * An implementation may choose to not execute the stream pipeline (either 642 * sequentially or in parallel) if it is capable of computing the count 643 * directly from the stream source. In such cases no source elements will 644 * be traversed and no intermediate operations will be evaluated. 645 * Behavioral parameters with side-effects, which are strongly discouraged 646 * except for harmless cases such as debugging, may be affected. For 647 * example, consider the following stream: 648 * <pre>{@code 649 * LongStream s = LongStream.of(1, 2, 3, 4); 650 * long count = s.peek(System.out::println).count(); 651 * }</pre> 652 * The number of elements covered by the stream source is known and the 653 * intermediate operation, {@code peek}, does not inject into or remove 654 * elements from the stream (as may be the case for {@code flatMap} or 655 * {@code filter} operations). Thus the count is 4 and there is no need to 656 * execute the pipeline and, as a side-effect, print out the elements. 657 * 658 * @return the count of elements in this stream 659 */ 660 long count(); 661 662 /** 663 * Returns an {@code OptionalDouble} describing the arithmetic mean of elements of 664 * this stream, or an empty optional if this stream is empty. This is a 665 * special case of a 666 * <a href="package-summary.html#Reduction">reduction</a>. 667 * 668 * <p>This is a <a href="package-summary.html#StreamOps">terminal 669 * operation</a>. 670 * 671 * @return an {@code OptionalDouble} containing the average element of this 672 * stream, or an empty optional if the stream is empty 673 */ 674 OptionalDouble average(); 675 676 /** 677 * Returns a {@code LongSummaryStatistics} describing various summary data 678 * about the elements of this stream. This is a special case of a 679 * <a href="package-summary.html#Reduction">reduction</a>. 680 * 681 * <p>This is a <a href="package-summary.html#StreamOps">terminal 682 * operation</a>. 683 * 684 * @return a {@code LongSummaryStatistics} describing various summary data 685 * about the elements of this stream 686 */ 687 LongSummaryStatistics summaryStatistics(); 688 689 /** 690 * Returns whether any elements of this stream match the provided 691 * predicate. May not evaluate the predicate on all elements if not 692 * necessary for determining the result. If the stream is empty then 693 * {@code false} is returned and the predicate is not evaluated. 694 * 695 * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting 696 * terminal operation</a>. 697 * 698 * @apiNote 699 * This method evaluates the <em>existential quantification</em> of the 700 * predicate over the elements of the stream (for some x P(x)). 701 * 702 * @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>, 703 * <a href="package-summary.html#Statelessness">stateless</a> 704 * predicate to apply to elements of this stream 705 * @return {@code true} if any elements of the stream match the provided 706 * predicate, otherwise {@code false} 707 */ 708 boolean anyMatch(LongPredicate predicate); 709 710 /** 711 * Returns whether all elements of this stream match the provided predicate. 712 * May not evaluate the predicate on all elements if not necessary for 713 * determining the result. If the stream is empty then {@code true} is 714 * returned and the predicate is not evaluated. 715 * 716 * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting 717 * terminal operation</a>. 718 * 719 * @apiNote 720 * This method evaluates the <em>universal quantification</em> of the 721 * predicate over the elements of the stream (for all x P(x)). If the 722 * stream is empty, the quantification is said to be <em>vacuously 723 * satisfied</em> and is always {@code true} (regardless of P(x)). 724 * 725 * @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>, 726 * <a href="package-summary.html#Statelessness">stateless</a> 727 * predicate to apply to elements of this stream 728 * @return {@code true} if either all elements of the stream match the 729 * provided predicate or the stream is empty, otherwise {@code false} 730 */ 731 boolean allMatch(LongPredicate predicate); 732 733 /** 734 * Returns whether no elements of this stream match the provided predicate. 735 * May not evaluate the predicate on all elements if not necessary for 736 * determining the result. If the stream is empty then {@code true} is 737 * returned and the predicate is not evaluated. 738 * 739 * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting 740 * terminal operation</a>. 741 * 742 * @apiNote 743 * This method evaluates the <em>universal quantification</em> of the 744 * negated predicate over the elements of the stream (for all x ~P(x)). If 745 * the stream is empty, the quantification is said to be vacuously satisfied 746 * and is always {@code true}, regardless of P(x). 747 * 748 * @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>, 749 * <a href="package-summary.html#Statelessness">stateless</a> 750 * predicate to apply to elements of this stream 751 * @return {@code true} if either no elements of the stream match the 752 * provided predicate or the stream is empty, otherwise {@code false} 753 */ 754 boolean noneMatch(LongPredicate predicate); 755 756 /** 757 * Returns an {@link OptionalLong} describing the first element of this 758 * stream, or an empty {@code OptionalLong} if the stream is empty. If the 759 * stream has no encounter order, then any element may be returned. 760 * 761 * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting 762 * terminal operation</a>. 763 * 764 * @return an {@code OptionalLong} describing the first element of this 765 * stream, or an empty {@code OptionalLong} if the stream is empty 766 */ 767 OptionalLong findFirst(); 768 769 /** 770 * Returns an {@link OptionalLong} describing some element of the stream, or 771 * an empty {@code OptionalLong} if the stream is empty. 772 * 773 * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting 774 * terminal operation</a>. 775 * 776 * <p>The behavior of this operation is explicitly nondeterministic; it is 777 * free to select any element in the stream. This is to allow for maximal 778 * performance in parallel operations; the cost is that multiple invocations 779 * on the same source may not return the same result. (If a stable result 780 * is desired, use {@link #findFirst()} instead.) 781 * 782 * @return an {@code OptionalLong} describing some element of this stream, 783 * or an empty {@code OptionalLong} if the stream is empty 784 * @see #findFirst() 785 */ 786 OptionalLong findAny(); 787 788 /** 789 * Returns a {@code DoubleStream} consisting of the elements of this stream, 790 * converted to {@code double}. 791 * 792 * <p>This is an <a href="package-summary.html#StreamOps">intermediate 793 * operation</a>. 794 * 795 * @return a {@code DoubleStream} consisting of the elements of this stream, 796 * converted to {@code double} 797 */ 798 DoubleStream asDoubleStream(); 799 800 /** 801 * Returns a {@code Stream} consisting of the elements of this stream, 802 * each boxed to a {@code Long}. 803 * 804 * <p>This is an <a href="package-summary.html#StreamOps">intermediate 805 * operation</a>. 806 * 807 * @return a {@code Stream} consistent of the elements of this stream, 808 * each boxed to {@code Long} 809 */ 810 Stream<Long> boxed(); 811 812 @Override 813 LongStream sequential(); 814 815 @Override 816 LongStream parallel(); 817 818 @Override 819 PrimitiveIterator.OfLong iterator(); 820 821 @Override 822 Spliterator.OfLong spliterator(); 823 824 // Static factories 825 826 /** 827 * Returns a builder for a {@code LongStream}. 828 * 829 * @return a stream builder 830 */ 831 public static Builder builder() { 832 return new Streams.LongStreamBuilderImpl(); 833 } 834 835 /** 836 * Returns an empty sequential {@code LongStream}. 837 * 838 * @return an empty sequential stream 839 */ 840 public static LongStream empty() { 841 return StreamSupport.longStream(Spliterators.emptyLongSpliterator(), false); 842 } 843 844 /** 845 * Returns a sequential {@code LongStream} containing a single element. 846 * 847 * @param t the single element 848 * @return a singleton sequential stream 849 */ 850 public static LongStream of(long t) { 851 return StreamSupport.longStream(new Streams.LongStreamBuilderImpl(t), false); 852 } 853 854 /** 855 * Returns a sequential ordered stream whose elements are the specified values. 856 * 857 * @param values the elements of the new stream 858 * @return the new stream 859 */ 860 public static LongStream of(long... values) { 861 return Arrays.stream(values); 862 } 863 864 /** 865 * Returns an infinite sequential ordered {@code LongStream} produced by iterative 866 * application of a function {@code f} to an initial element {@code seed}, 867 * producing a {@code Stream} consisting of {@code seed}, {@code f(seed)}, 868 * {@code f(f(seed))}, etc. 869 * 870 * <p>The first element (position {@code 0}) in the {@code LongStream} will 871 * be the provided {@code seed}. For {@code n > 0}, the element at position 872 * {@code n}, will be the result of applying the function {@code f} to the 873 * element at position {@code n - 1}. 874 * 875 * @param seed the initial element 876 * @param f a function to be applied to the previous element to produce 877 * a new element 878 * @return a new sequential {@code LongStream} 879 */ 880 public static LongStream iterate(final long seed, final LongUnaryOperator f) { 881 Objects.requireNonNull(f); 882 final PrimitiveIterator.OfLong iterator = new PrimitiveIterator.OfLong() { 883 long t = seed; 884 885 @Override 886 public boolean hasNext() { 887 return true; 888 } 889 890 @Override 891 public long nextLong() { 892 long v = t; 893 t = f.applyAsLong(t); 894 return v; 895 } 896 }; 897 return StreamSupport.longStream(Spliterators.spliteratorUnknownSize( 898 iterator, 899 Spliterator.ORDERED | Spliterator.IMMUTABLE | Spliterator.NONNULL), false); 900 } 901 902 /** 903 * Returns an infinite sequential unordered stream where each element is 904 * generated by the provided {@code LongSupplier}. This is suitable for 905 * generating constant streams, streams of random elements, etc. 906 * 907 * @param s the {@code LongSupplier} for generated elements 908 * @return a new infinite sequential unordered {@code LongStream} 909 */ 910 public static LongStream generate(LongSupplier s) { 911 Objects.requireNonNull(s); 912 return StreamSupport.longStream( 913 new StreamSpliterators.InfiniteSupplyingSpliterator.OfLong(Long.MAX_VALUE, s), false); 914 } 915 916 /** 917 * Returns a sequential ordered {@code LongStream} from {@code startInclusive} 918 * (inclusive) to {@code endExclusive} (exclusive) by an incremental step of 919 * {@code 1}. 920 * 921 * @apiNote 922 * <p>An equivalent sequence of increasing values can be produced 923 * sequentially using a {@code for} loop as follows: 924 * <pre>{@code 925 * for (long i = startInclusive; i < endExclusive ; i++) { ... } 926 * }</pre> 927 * 928 * @param startInclusive the (inclusive) initial value 929 * @param endExclusive the exclusive upper bound 930 * @return a sequential {@code LongStream} for the range of {@code long} 931 * elements 932 */ 933 public static LongStream range(long startInclusive, final long endExclusive) { 934 if (startInclusive >= endExclusive) { 935 return empty(); 936 } else if (endExclusive - startInclusive < 0) { 937 // Size of range > Long.MAX_VALUE 938 // Split the range in two and concatenate 939 // Note: if the range is [Long.MIN_VALUE, Long.MAX_VALUE) then 940 // the lower range, [Long.MIN_VALUE, 0) will be further split in two 941 long m = startInclusive + Long.divideUnsigned(endExclusive - startInclusive, 2) + 1; 942 return concat(range(startInclusive, m), range(m, endExclusive)); 943 } else { 944 return StreamSupport.longStream( 945 new Streams.RangeLongSpliterator(startInclusive, endExclusive, false), false); 946 } 947 } 948 949 /** 950 * Returns a sequential ordered {@code LongStream} from {@code startInclusive} 951 * (inclusive) to {@code endInclusive} (inclusive) by an incremental step of 952 * {@code 1}. 953 * 954 * @apiNote 955 * <p>An equivalent sequence of increasing values can be produced 956 * sequentially using a {@code for} loop as follows: 957 * <pre>{@code 958 * for (long i = startInclusive; i <= endInclusive ; i++) { ... } 959 * }</pre> 960 * 961 * @param startInclusive the (inclusive) initial value 962 * @param endInclusive the inclusive upper bound 963 * @return a sequential {@code LongStream} for the range of {@code long} 964 * elements 965 */ 966 public static LongStream rangeClosed(long startInclusive, final long endInclusive) { 967 if (startInclusive > endInclusive) { 968 return empty(); 969 } else if (endInclusive - startInclusive + 1 <= 0) { 970 // Size of range > Long.MAX_VALUE 971 // Split the range in two and concatenate 972 // Note: if the range is [Long.MIN_VALUE, Long.MAX_VALUE] then 973 // the lower range, [Long.MIN_VALUE, 0), and upper range, 974 // [0, Long.MAX_VALUE], will both be further split in two 975 long m = startInclusive + Long.divideUnsigned(endInclusive - startInclusive, 2) + 1; 976 return concat(range(startInclusive, m), rangeClosed(m, endInclusive)); 977 } else { 978 return StreamSupport.longStream( 979 new Streams.RangeLongSpliterator(startInclusive, endInclusive, true), false); 980 } 981 } 982 983 /** 984 * Creates a lazily concatenated stream whose elements are all the 985 * elements of the first stream followed by all the elements of the 986 * second stream. The resulting stream is ordered if both 987 * of the input streams are ordered, and parallel if either of the input 988 * streams is parallel. When the resulting stream is closed, the close 989 * handlers for both input streams are invoked. 990 * 991 * @implNote 992 * Use caution when constructing streams from repeated concatenation. 993 * Accessing an element of a deeply concatenated stream can result in deep 994 * call chains, or even {@code StackOverflowError}. 995 * 996 * @param a the first stream 997 * @param b the second stream 998 * @return the concatenation of the two input streams 999 */ 1000 public static LongStream concat(LongStream a, LongStream b) { 1001 Objects.requireNonNull(a); 1002 Objects.requireNonNull(b); 1003 1004 Spliterator.OfLong split = new Streams.ConcatSpliterator.OfLong( 1005 a.spliterator(), b.spliterator()); 1006 LongStream stream = StreamSupport.longStream(split, a.isParallel() || b.isParallel()); 1007 return stream.onClose(Streams.composedClose(a, b)); 1008 } 1009 1010 /** 1011 * A mutable builder for a {@code LongStream}. 1012 * 1013 * <p>A stream builder has a lifecycle, which starts in a building 1014 * phase, during which elements can be added, and then transitions to a built 1015 * phase, after which elements may not be added. The built phase begins 1016 * begins when the {@link #build()} method is called, which creates an 1017 * ordered stream whose elements are the elements that were added to the 1018 * stream builder, in the order they were added. 1019 * 1020 * @see LongStream#builder() 1021 * @since 1.8 1022 */ 1023 public interface Builder extends LongConsumer { 1024 1025 /** 1026 * Adds an element to the stream being built. 1027 * 1028 * @throws IllegalStateException if the builder has already transitioned 1029 * to the built state 1030 */ 1031 @Override 1032 void accept(long t); 1033 1034 /** 1035 * Adds an element to the stream being built. 1036 * 1037 * @implSpec 1038 * The default implementation behaves as if: 1039 * <pre>{@code 1040 * accept(t) 1041 * return this; 1042 * }</pre> 1043 * 1044 * @param t the element to add 1045 * @return {@code this} builder 1046 * @throws IllegalStateException if the builder has already transitioned 1047 * to the built state 1048 */ 1049 default Builder add(long t) { 1050 accept(t); 1051 return this; 1052 } 1053 1054 /** 1055 * Builds the stream, transitioning this builder to the built state. 1056 * An {@code IllegalStateException} is thrown if there are further 1057 * attempts to operate on the builder after it has entered the built 1058 * state. 1059 * 1060 * @return the built stream 1061 * @throws IllegalStateException if the builder has already transitioned 1062 * to the built state 1063 */ 1064 LongStream build(); 1065 } 1066 }