Java Streams - LongStream limit(long maxSize) example








LongStream limit(long maxSize) returns a stream consisting of the elements of this stream, truncated to be no longer than maxSize in length. This is a short-circuiting stateful intermediate operation.

Syntax

limit has the following syntax.

LongStream limit(long maxSize)

Example

The following example shows how to use limit.

import java.util.stream.LongStream;

public class Main {
  public static void main(String[] args) {
    LongStream b = LongStream.of(1L, 2L, Long.MAX_VALUE, Long.MIN_VALUE);

    b.limit(2).forEach(System.out::println);
  }
}

The code above generates the following result.