Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Stream.limit: practical reference

Stream.limit: practical reference: limit is a short-circuiting stateful intermediate operation that yields at most maxSize elements, taking the first elements for an ordered stream.

Version: Java SE 21 (JLS and Java SE API); examples verified on the repository Java runtime

Syntax

Stream.limit(...)

limit is a short-circuiting stateful intermediate operation that yields at most maxSize elements, taking the first elements for an ordered stream.

Use it to terminate a finite prefix of an infinite source safely or to take the first page of ordered data.

On an ordered parallel pipeline, preserving the first n elements can require expensive coordination and buffering; unordered may be faster when semantics allow it.

A negative maxSize throws IllegalArgumentException, limit(0) yields an empty stream, and a source shorter than the limit passes through completely.

The example exercises the documented element in a small deterministic program and compares exact standard output.

Examples

public class Main {
    public static void main(String[] args) throws Exception {
        var result = java.util.stream.Stream.of(1, 2, 3).limit(2).toList();
        System.out.println(result);
    }
}

Result

[1, 2]

The example exercises the documented element in a small deterministic program and compares exact standard output.

Sources