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
Syntax
stream.limit(maxSize)
Parameters
| Parameter | Description |
|---|---|
maxSizelong |
How many elements to keep. |
Return value
A new Stream<T>.
Examples
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.
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
| Version | Change |
|---|---|
| Java Java 8 | Added |
Related
stream.sorted()· Return a stream sorted by natural order or by a Comparator. The source collection is not changed.- Java Streams · tutorial