Java Streams - Stream limit(long maxSize) example








Stream limit(long maxSize) returns a stream consisting of the elements of this stream, truncated to be no longer than maxSize in length.

Syntax

limit has the following syntax.

Stream<T> limit(long maxSize)

Example

The following example shows how to use limit.

import java.util.Arrays;
import java.util.List;
//  w w w  .  j  a  v  a 2 s.c om
public class Main {
  public static void main(String[] args) {
    List<String> stringList = Arrays.asList("1","1","2","3","4");

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

The code above generates the following result.