Java 25 (LTS) reference · Stream API

Java Stream limit() Method

Keep at most the first n elements. skip(n) drops the first n. Together they paginate a stream.

Java 25 (LTS) Since Java 8

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

stream.limit(maxSize)

Parameters

ParameterDescription
maxSize
long
How many elements to keep.

Return value

A new Stream<T>.

Examples

Page 2 of 3 per page
import java.util.*;
import java.util.stream.*;

public class Main {
    public static void main(String[] args) {
        List<Integer> nums = List.of(10, 20, 30, 40, 50, 60, 70);
        int page = 2, size = 3;
        System.out.println(nums.stream().skip((long) (page - 1) * size).limit(size).toList());
    }
}

Output

[40, 50, 60]

Run this on your computer — see “Get Started” for setup.

Limit an infinite stream
import java.util.*;
import java.util.stream.*;

public class Main {
    public static void main(String[] args) {
        System.out.println(Stream.iterate(1, n -> n * 2).limit(8).toList());
    }
}

Output

[1, 2, 4, 8, 16, 32, 64, 128]

Run this on your computer — see “Get Started” for setup.

Version history

VersionChange
Java Java 8Added

Was this page helpful?