1 /* 2 * Copyright (c) 2013, 2016, Oracle and/or its affiliates. All rights reserved. 3 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. 4 * 5 * This code is free software; you can redistribute it and/or modify it 6 * under the terms of the GNU General Public License version 2 only, as 7 * published by the Free Software Foundation. Oracle designates this 8 * particular file as subject to the "Classpath" exception as provided 9 * by Oracle in the LICENSE file that accompanied this code. 10 * 11 * This code is distributed in the hope that it will be useful, but WITHOUT 12 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 13 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License 14 * version 2 for more details (a copy is included in the LICENSE file that 15 * accompanied this code). 16 * 17 * You should have received a copy of the GNU General Public License version 18 * 2 along with this work; if not, write to the Free Software Foundation, 19 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. 20 * 21 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA 22 * or visit www.oracle.com if you need additional information or have any 23 * questions. 24 */ 25 package java.util.stream; 26 27 import java.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 * <p>In cases where the stream implementation is able to optimize away the 213 * production of some or all the elements (such as with short-circuiting 214 * operations like {@code findFirst}, or in the example described in 215 * {@link #count}), the action will not be invoked for those elements. 216 * 217 * @param action a <a href="package-summary.html#NonInterference"> 218 * non-interfering</a> action to perform on the elements as 219 * they are consumed from the stream 220 * @return the new stream 221 */ 222 LongStream peek(LongConsumer action); 223 224 /** 225 * Returns a stream consisting of the elements of this stream, truncated 226 * to be no longer than {@code maxSize} in length. 227 * 228 * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting 229 * stateful intermediate operation</a>. 230 * 231 * @apiNote 232 * While {@code limit()} is generally a cheap operation on sequential 233 * stream pipelines, it can be quite expensive on ordered parallel pipelines, 234 * especially for large values of {@code maxSize}, since {@code limit(n)} 235 * is constrained to return not just any <em>n</em> elements, but the 236 * <em>first n</em> elements in the encounter order. Using an unordered 237 * stream source (such as {@link #generate(LongSupplier)}) or removing the 238 * ordering constraint with {@link #unordered()} may result in significant 239 * speedups of {@code limit()} in parallel pipelines, if the semantics of 240 * your situation permit. If consistency with encounter order is required, 241 * and you are experiencing poor performance or memory utilization with 242 * {@code limit()} in parallel pipelines, switching to sequential execution 243 * with {@link #sequential()} may improve performance. 244 * 245 * @param maxSize the number of elements the stream should be limited to 246 * @return the new stream 247 * @throws IllegalArgumentException if {@code maxSize} is negative 248 */ 249 LongStream limit(long maxSize); 250 251 /** 252 * Returns a stream consisting of the remaining elements of this stream 253 * after discarding the first {@code n} elements of the stream. 254 * If this stream contains fewer than {@code n} elements then an 255 * empty stream will be returned. 256 * 257 * <p>This is a <a href="package-summary.html#StreamOps">stateful 258 * intermediate operation</a>. 259 * 260 * @apiNote 261 * While {@code skip()} is generally a cheap operation on sequential 262 * stream pipelines, it can be quite expensive on ordered parallel pipelines, 263 * especially for large values of {@code n}, since {@code skip(n)} 264 * is constrained to skip not just any <em>n</em> elements, but the 265 * <em>first n</em> elements in the encounter order. Using an unordered 266 * stream source (such as {@link #generate(LongSupplier)}) or removing the 267 * ordering constraint with {@link #unordered()} may result in significant 268 * speedups of {@code skip()} in parallel pipelines, if the semantics of 269 * your situation permit. If consistency with encounter order is required, 270 * and you are experiencing poor performance or memory utilization with 271 * {@code skip()} in parallel pipelines, switching to sequential execution 272 * with {@link #sequential()} may improve performance. 273 * 274 * @param n the number of leading elements to skip 275 * @return the new stream 276 * @throws IllegalArgumentException if {@code n} is negative 277 */ 278 LongStream skip(long n); 279 280 /** 281 * Returns, if this stream is ordered, a stream consisting of the longest 282 * prefix of elements taken from this stream that match the given predicate. 283 * Otherwise returns, if this stream is unordered, a stream consisting of a 284 * subset of elements taken from this stream that match the given predicate. 285 * 286 * <p>If this stream is ordered then the longest prefix is a contiguous 287 * sequence of elements of this stream that match the given predicate. The 288 * first element of the sequence is the first element of this stream, and 289 * the element immediately following the last element of the sequence does 290 * not match the given predicate. 291 * 292 * <p>If this stream is unordered, and some (but not all) elements of this 293 * stream match the given predicate, then the behavior of this operation is 294 * nondeterministic; it is free to take any subset of matching elements 295 * (which includes the empty set). 296 * 297 * <p>Independent of whether this stream is ordered or unordered if all 298 * elements of this stream match the given predicate then this operation 299 * takes all elements (the result is the same as the input), or if no 300 * elements of the stream match the given predicate then no elements are 301 * taken (the result is an empty stream). 302 * 303 * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting 304 * stateful intermediate operation</a>. 305 * 306 * @implSpec 307 * The default implementation obtains the {@link #spliterator() spliterator} 308 * of this stream, wraps that spliterator so as to support the semantics 309 * of this operation on traversal, and returns a new stream associated with 310 * the wrapped spliterator. The returned stream preserves the execution 311 * characteristics of this stream (namely parallel or sequential execution 312 * as per {@link #isParallel()}) but the wrapped spliterator may choose to 313 * not support splitting. When the returned stream is closed, the close 314 * handlers for both the returned and this stream are invoked. 315 * 316 * @apiNote 317 * While {@code takeWhile()} is generally a cheap operation on sequential 318 * stream pipelines, it can be quite expensive on ordered parallel 319 * pipelines, since the operation is constrained to return not just any 320 * valid prefix, but the longest prefix of elements in the encounter order. 321 * Using an unordered stream source (such as 322 * {@link #generate(LongSupplier)}) or removing the ordering constraint with 323 * {@link #unordered()} may result in significant speedups of 324 * {@code takeWhile()} in parallel pipelines, if the semantics of your 325 * situation permit. If consistency with encounter order is required, and 326 * you are experiencing poor performance or memory utilization with 327 * {@code takeWhile()} in parallel pipelines, switching to sequential 328 * execution with {@link #sequential()} may improve performance. 329 * 330 * @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>, 331 * <a href="package-summary.html#Statelessness">stateless</a> 332 * predicate to apply to elements to determine the longest 333 * prefix of elements. 334 * @return the new stream 335 * @since 9 336 */ 337 default LongStream takeWhile(LongPredicate predicate) { 338 Objects.requireNonNull(predicate); 339 // Reuses the unordered spliterator, which, when encounter is present, 340 // is safe to use as long as it configured not to split 341 return StreamSupport.longStream( 342 new WhileOps.UnorderedWhileSpliterator.OfLong.Taking(spliterator(), true, predicate), 343 isParallel()).onClose(this::close); 344 } 345 346 /** 347 * Returns, if this stream is ordered, a stream consisting of the remaining 348 * elements of this stream after dropping the longest prefix of elements 349 * that match the given predicate. Otherwise returns, if this stream is 350 * unordered, a stream consisting of the remaining elements of this stream 351 * after dropping a subset of elements that match the given predicate. 352 * 353 * <p>If this stream is ordered then the longest prefix is a contiguous 354 * sequence of elements of this stream that match the given predicate. The 355 * first element of the sequence is the first element of this stream, and 356 * the element immediately following the last element of the sequence does 357 * not match the given predicate. 358 * 359 * <p>If this stream is unordered, and some (but not all) elements of this 360 * stream match the given predicate, then the behavior of this operation is 361 * nondeterministic; it is free to drop any subset of matching elements 362 * (which includes the empty set). 363 * 364 * <p>Independent of whether this stream is ordered or unordered if all 365 * elements of this stream match the given predicate then this operation 366 * drops all elements (the result is an empty stream), or if no elements of 367 * the stream match the given predicate then no elements are dropped (the 368 * result is the same as the input). 369 * 370 * <p>This is a <a href="package-summary.html#StreamOps">stateful 371 * intermediate operation</a>. 372 * 373 * @implSpec 374 * The default implementation obtains the {@link #spliterator() spliterator} 375 * of this stream, wraps that spliterator so as to support the semantics 376 * of this operation on traversal, and returns a new stream associated with 377 * the wrapped spliterator. The returned stream preserves the execution 378 * characteristics of this stream (namely parallel or sequential execution 379 * as per {@link #isParallel()}) but the wrapped spliterator may choose to 380 * not support splitting. When the returned stream is closed, the close 381 * handlers for both the returned and this stream are invoked. 382 * 383 * @apiNote 384 * While {@code dropWhile()} is generally a cheap operation on sequential 385 * stream pipelines, it can be quite expensive on ordered parallel 386 * pipelines, since the operation is constrained to return not just any 387 * valid prefix, but the longest prefix of elements in the encounter order. 388 * Using an unordered stream source (such as 389 * {@link #generate(LongSupplier)}) or removing the ordering constraint with 390 * {@link #unordered()} may result in significant speedups of 391 * {@code dropWhile()} in parallel pipelines, if the semantics of your 392 * situation permit. If consistency with encounter order is required, and 393 * you are experiencing poor performance or memory utilization with 394 * {@code dropWhile()} in parallel pipelines, switching to sequential 395 * execution with {@link #sequential()} may improve performance. 396 * 397 * @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>, 398 * <a href="package-summary.html#Statelessness">stateless</a> 399 * predicate to apply to elements to determine the longest 400 * prefix of elements. 401 * @return the new stream 402 * @since 9 403 */ 404 default LongStream dropWhile(LongPredicate predicate) { 405 Objects.requireNonNull(predicate); 406 // Reuses the unordered spliterator, which, when encounter is present, 407 // is safe to use as long as it configured not to split 408 return StreamSupport.longStream( 409 new WhileOps.UnorderedWhileSpliterator.OfLong.Dropping(spliterator(), true, predicate), 410 isParallel()).onClose(this::close); 411 } 412 413 /** 414 * Performs an action for each element of this stream. 415 * 416 * <p>This is a <a href="package-summary.html#StreamOps">terminal 417 * operation</a>. 418 * 419 * <p>For parallel stream pipelines, this operation does <em>not</em> 420 * guarantee to respect the encounter order of the stream, as doing so 421 * would sacrifice the benefit of parallelism. For any given element, the 422 * action may be performed at whatever time and in whatever thread the 423 * library chooses. If the action accesses shared state, it is 424 * responsible for providing the required synchronization. 425 * 426 * @param action a <a href="package-summary.html#NonInterference"> 427 * non-interfering</a> action to perform on the elements 428 */ 429 void forEach(LongConsumer action); 430 431 /** 432 * Performs an action for each element of this stream, guaranteeing that 433 * each element is processed in encounter order for streams that have a 434 * defined encounter order. 435 * 436 * <p>This is a <a href="package-summary.html#StreamOps">terminal 437 * operation</a>. 438 * 439 * @param action a <a href="package-summary.html#NonInterference"> 440 * non-interfering</a> action to perform on the elements 441 * @see #forEach(LongConsumer) 442 */ 443 void forEachOrdered(LongConsumer action); 444 445 /** 446 * Returns an array containing the elements of this stream. 447 * 448 * <p>This is a <a href="package-summary.html#StreamOps">terminal 449 * operation</a>. 450 * 451 * @return an array containing the elements of this stream 452 */ 453 long[] toArray(); 454 455 /** 456 * Performs a <a href="package-summary.html#Reduction">reduction</a> on the 457 * elements of this stream, using the provided identity value and an 458 * <a href="package-summary.html#Associativity">associative</a> 459 * accumulation function, and returns the reduced value. This is equivalent 460 * to: 461 * <pre>{@code 462 * long result = identity; 463 * for (long element : this stream) 464 * result = accumulator.applyAsLong(result, element) 465 * return result; 466 * }</pre> 467 * 468 * but is not constrained to execute sequentially. 469 * 470 * <p>The {@code identity} value must be an identity for the accumulator 471 * function. This means that for all {@code x}, 472 * {@code accumulator.apply(identity, x)} is equal to {@code x}. 473 * The {@code accumulator} function must be an 474 * <a href="package-summary.html#Associativity">associative</a> function. 475 * 476 * <p>This is a <a href="package-summary.html#StreamOps">terminal 477 * operation</a>. 478 * 479 * @apiNote Sum, min, max, and average are all special cases of reduction. 480 * Summing a stream of numbers can be expressed as: 481 * 482 * <pre>{@code 483 * long sum = integers.reduce(0, (a, b) -> a+b); 484 * }</pre> 485 * 486 * or more compactly: 487 * 488 * <pre>{@code 489 * long sum = integers.reduce(0, Long::sum); 490 * }</pre> 491 * 492 * <p>While this may seem a more roundabout way to perform an aggregation 493 * compared to simply mutating a running total in a loop, reduction 494 * operations parallelize more gracefully, without needing additional 495 * synchronization and with greatly reduced risk of data races. 496 * 497 * @param identity the identity value for the accumulating function 498 * @param op an <a href="package-summary.html#Associativity">associative</a>, 499 * <a href="package-summary.html#NonInterference">non-interfering</a>, 500 * <a href="package-summary.html#Statelessness">stateless</a> 501 * function for combining two values 502 * @return the result of the reduction 503 * @see #sum() 504 * @see #min() 505 * @see #max() 506 * @see #average() 507 */ 508 long reduce(long identity, LongBinaryOperator op); 509 510 /** 511 * Performs a <a href="package-summary.html#Reduction">reduction</a> on the 512 * elements of this stream, using an 513 * <a href="package-summary.html#Associativity">associative</a> accumulation 514 * function, and returns an {@code OptionalLong} describing the reduced value, 515 * if any. This is equivalent to: 516 * <pre>{@code 517 * boolean foundAny = false; 518 * long result = null; 519 * for (long element : this stream) { 520 * if (!foundAny) { 521 * foundAny = true; 522 * result = element; 523 * } 524 * else 525 * result = accumulator.applyAsLong(result, element); 526 * } 527 * return foundAny ? OptionalLong.of(result) : OptionalLong.empty(); 528 * }</pre> 529 * 530 * but is not constrained to execute sequentially. 531 * 532 * <p>The {@code accumulator} function must be an 533 * <a href="package-summary.html#Associativity">associative</a> function. 534 * 535 * <p>This is a <a href="package-summary.html#StreamOps">terminal 536 * operation</a>. 537 * 538 * @param op an <a href="package-summary.html#Associativity">associative</a>, 539 * <a href="package-summary.html#NonInterference">non-interfering</a>, 540 * <a href="package-summary.html#Statelessness">stateless</a> 541 * function for combining two values 542 * @return the result of the reduction 543 * @see #reduce(long, LongBinaryOperator) 544 */ 545 OptionalLong reduce(LongBinaryOperator op); 546 547 /** 548 * Performs a <a href="package-summary.html#MutableReduction">mutable 549 * reduction</a> operation on the elements of this stream. A mutable 550 * reduction is one in which the reduced value is a mutable result container, 551 * such as an {@code ArrayList}, and elements are incorporated by updating 552 * the state of the result rather than by replacing the result. This 553 * produces a result equivalent to: 554 * <pre>{@code 555 * R result = supplier.get(); 556 * for (long element : this stream) 557 * accumulator.accept(result, element); 558 * return result; 559 * }</pre> 560 * 561 * <p>Like {@link #reduce(long, LongBinaryOperator)}, {@code collect} operations 562 * can be parallelized without requiring additional synchronization. 563 * 564 * <p>This is a <a href="package-summary.html#StreamOps">terminal 565 * operation</a>. 566 * 567 * @param <R> the type of the mutable result container 568 * @param supplier a function that creates a new mutable result container. 569 * For a parallel execution, this function may be called 570 * multiple times and must return a fresh value each time. 571 * @param accumulator an <a href="package-summary.html#Associativity">associative</a>, 572 * <a href="package-summary.html#NonInterference">non-interfering</a>, 573 * <a href="package-summary.html#Statelessness">stateless</a> 574 * function that must fold an element into a result 575 * container. 576 * @param combiner an <a href="package-summary.html#Associativity">associative</a>, 577 * <a href="package-summary.html#NonInterference">non-interfering</a>, 578 * <a href="package-summary.html#Statelessness">stateless</a> 579 * function that accepts two partial result containers 580 * and merges them, which must be compatible with the 581 * accumulator function. The combiner function must fold 582 * the elements from the second result container into the 583 * first result container. 584 * @return the result of the reduction 585 * @see Stream#collect(Supplier, BiConsumer, BiConsumer) 586 */ 587 <R> R collect(Supplier<R> supplier, 588 ObjLongConsumer<R> accumulator, 589 BiConsumer<R, R> combiner); 590 591 /** 592 * Returns the sum of elements in this stream. This is a special case 593 * of a <a href="package-summary.html#Reduction">reduction</a> 594 * and is equivalent to: 595 * <pre>{@code 596 * return reduce(0, Long::sum); 597 * }</pre> 598 * 599 * <p>This is a <a href="package-summary.html#StreamOps">terminal 600 * operation</a>. 601 * 602 * @return the sum of elements in this stream 603 */ 604 long sum(); 605 606 /** 607 * Returns an {@code OptionalLong} describing the minimum element of this 608 * stream, or an empty optional if this stream is empty. This is a special 609 * case of a <a href="package-summary.html#Reduction">reduction</a> 610 * and is equivalent to: 611 * <pre>{@code 612 * return reduce(Long::min); 613 * }</pre> 614 * 615 * <p>This is a <a href="package-summary.html#StreamOps">terminal operation</a>. 616 * 617 * @return an {@code OptionalLong} containing the minimum element of this 618 * stream, or an empty {@code OptionalLong} if the stream is empty 619 */ 620 OptionalLong min(); 621 622 /** 623 * Returns an {@code OptionalLong} describing the maximum element of this 624 * stream, or an empty optional if this stream is empty. This is a special 625 * case of a <a href="package-summary.html#Reduction">reduction</a> 626 * and is equivalent to: 627 * <pre>{@code 628 * return reduce(Long::max); 629 * }</pre> 630 * 631 * <p>This is a <a href="package-summary.html#StreamOps">terminal 632 * operation</a>. 633 * 634 * @return an {@code OptionalLong} containing the maximum element of this 635 * stream, or an empty {@code OptionalLong} if the stream is empty 636 */ 637 OptionalLong max(); 638 639 /** 640 * Returns the count of elements in this stream. This is a special case of 641 * a <a href="package-summary.html#Reduction">reduction</a> and is 642 * equivalent to: 643 * <pre>{@code 644 * return map(e -> 1L).sum(); 645 * }</pre> 646 * 647 * <p>This is a <a href="package-summary.html#StreamOps">terminal operation</a>. 648 * 649 * @apiNote 650 * An implementation may choose to not execute the stream pipeline (either 651 * sequentially or in parallel) if it is capable of computing the count 652 * directly from the stream source. In such cases no source elements will 653 * be traversed and no intermediate operations will be evaluated. 654 * Behavioral parameters with side-effects, which are strongly discouraged 655 * except for harmless cases such as debugging, may be affected. For 656 * example, consider the following stream: 657 * <pre>{@code 658 * LongStream s = LongStream.of(1, 2, 3, 4); 659 * long count = s.peek(System.out::println).count(); 660 * }</pre> 661 * The number of elements covered by the stream source is known and the 662 * intermediate operation, {@code peek}, does not inject into or remove 663 * elements from the stream (as may be the case for {@code flatMap} or 664 * {@code filter} operations). Thus the count is 4 and there is no need to 665 * execute the pipeline and, as a side-effect, print out the elements. 666 * 667 * @return the count of elements in this stream 668 */ 669 long count(); 670 671 /** 672 * Returns an {@code OptionalDouble} describing the arithmetic mean of elements of 673 * this stream, or an empty optional if this stream is empty. This is a 674 * special case of a 675 * <a href="package-summary.html#Reduction">reduction</a>. 676 * 677 * <p>This is a <a href="package-summary.html#StreamOps">terminal 678 * operation</a>. 679 * 680 * @return an {@code OptionalDouble} containing the average element of this 681 * stream, or an empty optional if the stream is empty 682 */ 683 OptionalDouble average(); 684 685 /** 686 * Returns a {@code LongSummaryStatistics} describing various summary data 687 * about the elements of this stream. This is a special case of a 688 * <a href="package-summary.html#Reduction">reduction</a>. 689 * 690 * <p>This is a <a href="package-summary.html#StreamOps">terminal 691 * operation</a>. 692 * 693 * @return a {@code LongSummaryStatistics} describing various summary data 694 * about the elements of this stream 695 */ 696 LongSummaryStatistics summaryStatistics(); 697 698 /** 699 * Returns whether any elements of this stream match the provided 700 * predicate. May not evaluate the predicate on all elements if not 701 * necessary for determining the result. If the stream is empty then 702 * {@code false} is returned and the predicate is not evaluated. 703 * 704 * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting 705 * terminal operation</a>. 706 * 707 * @apiNote 708 * This method evaluates the <em>existential quantification</em> of the 709 * predicate over the elements of the stream (for some x P(x)). 710 * 711 * @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>, 712 * <a href="package-summary.html#Statelessness">stateless</a> 713 * predicate to apply to elements of this stream 714 * @return {@code true} if any elements of the stream match the provided 715 * predicate, otherwise {@code false} 716 */ 717 boolean anyMatch(LongPredicate predicate); 718 719 /** 720 * Returns whether all elements of this stream match the provided predicate. 721 * May not evaluate the predicate on all elements if not necessary for 722 * determining the result. If the stream is empty then {@code true} is 723 * returned and the predicate is not evaluated. 724 * 725 * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting 726 * terminal operation</a>. 727 * 728 * @apiNote 729 * This method evaluates the <em>universal quantification</em> of the 730 * predicate over the elements of the stream (for all x P(x)). If the 731 * stream is empty, the quantification is said to be <em>vacuously 732 * satisfied</em> and is always {@code true} (regardless of P(x)). 733 * 734 * @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>, 735 * <a href="package-summary.html#Statelessness">stateless</a> 736 * predicate to apply to elements of this stream 737 * @return {@code true} if either all elements of the stream match the 738 * provided predicate or the stream is empty, otherwise {@code false} 739 */ 740 boolean allMatch(LongPredicate predicate); 741 742 /** 743 * Returns whether no elements of this stream match the provided predicate. 744 * May not evaluate the predicate on all elements if not necessary for 745 * determining the result. If the stream is empty then {@code true} is 746 * returned and the predicate is not evaluated. 747 * 748 * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting 749 * terminal operation</a>. 750 * 751 * @apiNote 752 * This method evaluates the <em>universal quantification</em> of the 753 * negated predicate over the elements of the stream (for all x ~P(x)). If 754 * the stream is empty, the quantification is said to be vacuously satisfied 755 * and is always {@code true}, regardless of P(x). 756 * 757 * @param predicate a <a href="package-summary.html#NonInterference">non-interfering</a>, 758 * <a href="package-summary.html#Statelessness">stateless</a> 759 * predicate to apply to elements of this stream 760 * @return {@code true} if either no elements of the stream match the 761 * provided predicate or the stream is empty, otherwise {@code false} 762 */ 763 boolean noneMatch(LongPredicate predicate); 764 765 /** 766 * Returns an {@link OptionalLong} describing the first element of this 767 * stream, or an empty {@code OptionalLong} if the stream is empty. If the 768 * stream has no encounter order, then any element may be returned. 769 * 770 * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting 771 * terminal operation</a>. 772 * 773 * @return an {@code OptionalLong} describing the first element of this 774 * stream, or an empty {@code OptionalLong} if the stream is empty 775 */ 776 OptionalLong findFirst(); 777 778 /** 779 * Returns an {@link OptionalLong} describing some element of the stream, or 780 * an empty {@code OptionalLong} if the stream is empty. 781 * 782 * <p>This is a <a href="package-summary.html#StreamOps">short-circuiting 783 * terminal operation</a>. 784 * 785 * <p>The behavior of this operation is explicitly nondeterministic; it is 786 * free to select any element in the stream. This is to allow for maximal 787 * performance in parallel operations; the cost is that multiple invocations 788 * on the same source may not return the same result. (If a stable result 789 * is desired, use {@link #findFirst()} instead.) 790 * 791 * @return an {@code OptionalLong} describing some element of this stream, 792 * or an empty {@code OptionalLong} if the stream is empty 793 * @see #findFirst() 794 */ 795 OptionalLong findAny(); 796 797 /** 798 * Returns a {@code DoubleStream} consisting of the elements of this stream, 799 * converted to {@code double}. 800 * 801 * <p>This is an <a href="package-summary.html#StreamOps">intermediate 802 * operation</a>. 803 * 804 * @return a {@code DoubleStream} consisting of the elements of this stream, 805 * converted to {@code double} 806 */ 807 DoubleStream asDoubleStream(); 808 809 /** 810 * Returns a {@code Stream} consisting of the elements of this stream, 811 * each boxed to a {@code Long}. 812 * 813 * <p>This is an <a href="package-summary.html#StreamOps">intermediate 814 * operation</a>. 815 * 816 * @return a {@code Stream} consistent of the elements of this stream, 817 * each boxed to {@code Long} 818 */ 819 Stream<Long> boxed(); 820 821 @Override 822 LongStream sequential(); 823 824 @Override 825 LongStream parallel(); 826 827 @Override 828 PrimitiveIterator.OfLong iterator(); 829 830 @Override 831 Spliterator.OfLong spliterator(); 832 833 // Static factories 834 835 /** 836 * Returns a builder for a {@code LongStream}. 837 * 838 * @return a stream builder 839 */ 840 public static Builder builder() { 841 return new Streams.LongStreamBuilderImpl(); 842 } 843 844 /** 845 * Returns an empty sequential {@code LongStream}. 846 * 847 * @return an empty sequential stream 848 */ 849 public static LongStream empty() { 850 return StreamSupport.longStream(Spliterators.emptyLongSpliterator(), false); 851 } 852 853 /** 854 * Returns a sequential {@code LongStream} containing a single element. 855 * 856 * @param t the single element 857 * @return a singleton sequential stream 858 */ 859 public static LongStream of(long t) { 860 return StreamSupport.longStream(new Streams.LongStreamBuilderImpl(t), false); 861 } 862 863 /** 864 * Returns a sequential ordered stream whose elements are the specified values. 865 * 866 * @param values the elements of the new stream 867 * @return the new stream 868 */ 869 public static LongStream of(long... values) { 870 return Arrays.stream(values); 871 } 872 873 /** 874 * Returns an infinite sequential ordered {@code LongStream} produced by iterative 875 * application of a function {@code f} to an initial element {@code seed}, 876 * producing a {@code Stream} consisting of {@code seed}, {@code f(seed)}, 877 * {@code f(f(seed))}, etc. 878 * 879 * <p>The first element (position {@code 0}) in the {@code LongStream} will 880 * be the provided {@code seed}. For {@code n > 0}, the element at position 881 * {@code n}, will be the result of applying the function {@code f} to the 882 * element at position {@code n - 1}. 883 * 884 * <p>The action of applying {@code f} for one element 885 * <a href="../concurrent/package-summary.html#MemoryVisibility"><i>happens-before</i></a> 886 * the action of applying {@code f} for subsequent elements. For any given 887 * element the action may be performed in whatever thread the library 888 * chooses. 889 * 890 * @param seed the initial element 891 * @param f a function to be applied to the previous element to produce 892 * a new element 893 * @return a new sequential {@code LongStream} 894 */ 895 public static LongStream iterate(final long seed, final LongUnaryOperator f) { 896 Objects.requireNonNull(f); 897 Spliterator.OfLong spliterator = new Spliterators.AbstractLongSpliterator(Long.MAX_VALUE, 898 Spliterator.ORDERED | Spliterator.IMMUTABLE | Spliterator.NONNULL) { 899 long prev; 900 boolean started; 901 902 @Override 903 public boolean tryAdvance(LongConsumer action) { 904 Objects.requireNonNull(action); 905 long t; 906 if (started) 907 t = f.applyAsLong(prev); 908 else { 909 t = seed; 910 started = true; 911 } 912 action.accept(prev = t); 913 return true; 914 } 915 }; 916 return StreamSupport.longStream(spliterator, false); 917 } 918 919 /** 920 * Returns a sequential ordered {@code LongStream} produced by iterative 921 * application of the given {@code next} function to an initial element, 922 * conditioned on satisfying the given {@code hasNext} predicate. The 923 * stream terminates as soon as the {@code hasNext} predicate returns false. 924 * 925 * <p>{@code LongStream.iterate} should produce the same sequence of elements as 926 * produced by the corresponding for-loop: 927 * <pre>{@code 928 * for (long index=seed; hasNext.test(index); index = next.applyAsLong(index)) { 929 * ... 930 * } 931 * }</pre> 932 * 933 * <p>The resulting sequence may be empty if the {@code hasNext} predicate 934 * does not hold on the seed value. Otherwise the first element will be the 935 * supplied {@code seed} value, the next element (if present) will be the 936 * result of applying the {@code next} function to the {@code seed} value, 937 * and so on iteratively until the {@code hasNext} predicate indicates that 938 * the stream should terminate. 939 * 940 * <p>The action of applying the {@code hasNext} predicate to an element 941 * <a href="../concurrent/package-summary.html#MemoryVisibility"><i>happens-before</i></a> 942 * the action of applying the {@code next} function to that element. The 943 * action of applying the {@code next} function for one element 944 * <i>happens-before</i> the action of applying the {@code hasNext} 945 * predicate for subsequent elements. For any given element an action may 946 * be performed in whatever thread the library chooses. 947 * 948 * @param seed the initial element 949 * @param hasNext a predicate to apply to elements to determine when the 950 * stream must terminate. 951 * @param next a function to be applied to the previous element to produce 952 * a new element 953 * @return a new sequential {@code LongStream} 954 * @since 9 955 */ 956 public static LongStream iterate(long seed, LongPredicate hasNext, LongUnaryOperator next) { 957 Objects.requireNonNull(next); 958 Objects.requireNonNull(hasNext); 959 Spliterator.OfLong spliterator = new Spliterators.AbstractLongSpliterator(Long.MAX_VALUE, 960 Spliterator.ORDERED | Spliterator.IMMUTABLE | Spliterator.NONNULL) { 961 long prev; 962 boolean started, finished; 963 964 @Override 965 public boolean tryAdvance(LongConsumer action) { 966 Objects.requireNonNull(action); 967 if (finished) 968 return false; 969 long t; 970 if (started) 971 t = next.applyAsLong(prev); 972 else { 973 t = seed; 974 started = true; 975 } 976 if (!hasNext.test(t)) { 977 finished = true; 978 return false; 979 } 980 action.accept(prev = t); 981 return true; 982 } 983 984 @Override 985 public void forEachRemaining(LongConsumer action) { 986 Objects.requireNonNull(action); 987 if (finished) 988 return; 989 finished = true; 990 long t = started ? next.applyAsLong(prev) : seed; 991 while (hasNext.test(t)) { 992 action.accept(t); 993 t = next.applyAsLong(t); 994 } 995 } 996 }; 997 return StreamSupport.longStream(spliterator, false); 998 } 999 1000 /** 1001 * Returns an infinite sequential unordered stream where each element is 1002 * generated by the provided {@code LongSupplier}. This is suitable for 1003 * generating constant streams, streams of random elements, etc. 1004 * 1005 * @param s the {@code LongSupplier} for generated elements 1006 * @return a new infinite sequential unordered {@code LongStream} 1007 */ 1008 public static LongStream generate(LongSupplier s) { 1009 Objects.requireNonNull(s); 1010 return StreamSupport.longStream( 1011 new StreamSpliterators.InfiniteSupplyingSpliterator.OfLong(Long.MAX_VALUE, s), false); 1012 } 1013 1014 /** 1015 * Returns a sequential ordered {@code LongStream} from {@code startInclusive} 1016 * (inclusive) to {@code endExclusive} (exclusive) by an incremental step of 1017 * {@code 1}. 1018 * 1019 * @apiNote 1020 * <p>An equivalent sequence of increasing values can be produced 1021 * sequentially using a {@code for} loop as follows: 1022 * <pre>{@code 1023 * for (long i = startInclusive; i < endExclusive ; i++) { ... } 1024 * }</pre> 1025 * 1026 * @param startInclusive the (inclusive) initial value 1027 * @param endExclusive the exclusive upper bound 1028 * @return a sequential {@code LongStream} for the range of {@code long} 1029 * elements 1030 */ 1031 public static LongStream range(long startInclusive, final long endExclusive) { 1032 if (startInclusive >= endExclusive) { 1033 return empty(); 1034 } else if (endExclusive - startInclusive < 0) { 1035 // Size of range > Long.MAX_VALUE 1036 // Split the range in two and concatenate 1037 // Note: if the range is [Long.MIN_VALUE, Long.MAX_VALUE) then 1038 // the lower range, [Long.MIN_VALUE, 0) will be further split in two 1039 long m = startInclusive + Long.divideUnsigned(endExclusive - startInclusive, 2) + 1; 1040 return concat(range(startInclusive, m), range(m, endExclusive)); 1041 } else { 1042 return StreamSupport.longStream( 1043 new Streams.RangeLongSpliterator(startInclusive, endExclusive, false), false); 1044 } 1045 } 1046 1047 /** 1048 * Returns a sequential ordered {@code LongStream} from {@code startInclusive} 1049 * (inclusive) to {@code endInclusive} (inclusive) by an incremental step of 1050 * {@code 1}. 1051 * 1052 * @apiNote 1053 * <p>An equivalent sequence of increasing values can be produced 1054 * sequentially using a {@code for} loop as follows: 1055 * <pre>{@code 1056 * for (long i = startInclusive; i <= endInclusive ; i++) { ... } 1057 * }</pre> 1058 * 1059 * @param startInclusive the (inclusive) initial value 1060 * @param endInclusive the inclusive upper bound 1061 * @return a sequential {@code LongStream} for the range of {@code long} 1062 * elements 1063 */ 1064 public static LongStream rangeClosed(long startInclusive, final long endInclusive) { 1065 if (startInclusive > endInclusive) { 1066 return empty(); 1067 } else if (endInclusive - startInclusive + 1 <= 0) { 1068 // Size of range > Long.MAX_VALUE 1069 // Split the range in two and concatenate 1070 // Note: if the range is [Long.MIN_VALUE, Long.MAX_VALUE] then 1071 // the lower range, [Long.MIN_VALUE, 0), and upper range, 1072 // [0, Long.MAX_VALUE], will both be further split in two 1073 long m = startInclusive + Long.divideUnsigned(endInclusive - startInclusive, 2) + 1; 1074 return concat(range(startInclusive, m), rangeClosed(m, endInclusive)); 1075 } else { 1076 return StreamSupport.longStream( 1077 new Streams.RangeLongSpliterator(startInclusive, endInclusive, true), false); 1078 } 1079 } 1080 1081 /** 1082 * Creates a lazily concatenated stream whose elements are all the 1083 * elements of the first stream followed by all the elements of the 1084 * second stream. The resulting stream is ordered if both 1085 * of the input streams are ordered, and parallel if either of the input 1086 * streams is parallel. When the resulting stream is closed, the close 1087 * handlers for both input streams are invoked. 1088 * 1089 * @implNote 1090 * Use caution when constructing streams from repeated concatenation. 1091 * Accessing an element of a deeply concatenated stream can result in deep 1092 * call chains, or even {@code StackOverflowError}. 1093 * 1094 * @param a the first stream 1095 * @param b the second stream 1096 * @return the concatenation of the two input streams 1097 */ 1098 public static LongStream concat(LongStream a, LongStream b) { 1099 Objects.requireNonNull(a); 1100 Objects.requireNonNull(b); 1101 1102 Spliterator.OfLong split = new Streams.ConcatSpliterator.OfLong( 1103 a.spliterator(), b.spliterator()); 1104 LongStream stream = StreamSupport.longStream(split, a.isParallel() || b.isParallel()); 1105 return stream.onClose(Streams.composedClose(a, b)); 1106 } 1107 1108 /** 1109 * A mutable builder for a {@code LongStream}. 1110 * 1111 * <p>A stream builder has a lifecycle, which starts in a building 1112 * phase, during which elements can be added, and then transitions to a built 1113 * phase, after which elements may not be added. The built phase begins 1114 * begins when the {@link #build()} method is called, which creates an 1115 * ordered stream whose elements are the elements that were added to the 1116 * stream builder, in the order they were added. 1117 * 1118 * @see LongStream#builder() 1119 * @since 1.8 1120 */ 1121 public interface Builder extends LongConsumer { 1122 1123 /** 1124 * Adds an element to the stream being built. 1125 * 1126 * @throws IllegalStateException if the builder has already transitioned 1127 * to the built state 1128 */ 1129 @Override 1130 void accept(long t); 1131 1132 /** 1133 * Adds an element to the stream being built. 1134 * 1135 * @implSpec 1136 * The default implementation behaves as if: 1137 * <pre>{@code 1138 * accept(t) 1139 * return this; 1140 * }</pre> 1141 * 1142 * @param t the element to add 1143 * @return {@code this} builder 1144 * @throws IllegalStateException if the builder has already transitioned 1145 * to the built state 1146 */ 1147 default Builder add(long t) { 1148 accept(t); 1149 return this; 1150 } 1151 1152 /** 1153 * Builds the stream, transitioning this builder to the built state. 1154 * An {@code IllegalStateException} is thrown if there are further 1155 * attempts to operate on the builder after it has entered the built 1156 * state. 1157 * 1158 * @return the built stream 1159 * @throws IllegalStateException if the builder has already transitioned 1160 * to the built state 1161 */ 1162 LongStream build(); 1163 } 1164 }