Stream limit(n) is used to retrieve a number of elements from the Stream while the count must not be greater than n. The
limit() method returns a new Stream consisting of the elements of the given stream, truncated to be no longer than
maxSize in length.
1. Stream limit() Method
Stream<T> limit(long maxSize)
maxSize the number of elements the stream should be limited to; and the method return value is a new
Stream consisting of elements picked from the original stream.
- Stream.limit() method is short-circuiting intermediate operation. An intermediate operation is short-circuiting if, when presented with infinite input, it may produce a finite stream as a result. Please note that a terminal operation is short-circuiting if, when presented with infinite input, it may terminate in finite time.
- It returns a stream consisting of the maximum elements, no longer than given size in length, of current stream.
limit()is cheap operation but may sometimes be expensive if
maxSizehas a large value and stream is parallely processed.
- Using an unordered stream source (such as
generate(Supplier)) or removing the ordering constraint with
BaseStream.unordered()may result in significant speedups of
limit()in parallel pipelines.
limit()returns the first n elements in the encounter order.
2. Stream limit() Examples
Example 1: Getting first 10 even numbers from an infinite stream of even numbers
In the given below example, we are creating an infinite stream using
iterate() method. Then we are taking the first 10 even numbers using the method
Finally, we are collecting the even numbers from the stream into a
Stream<Integer> evenNumInfiniteStream = Stream.iterate(0, n -> n + 2); List<Integer> newList = evenNumInfiniteStream.limit(10) .collect(Collectors.toList()); System.out.println(newList);
[0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
3. Difference between skip() and limit()
limit(N)method returns first
Nelements in the encounter order of the Stream.
skip(N)discards the first N elements of the Stream.
List<Integer> list = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) .skip(6) .collect(Collectors.toList()); System.out.println(newList); //[7, 8, 9, 10]
Java 8 Stream
limit() method can be useful in certain cases where we need to get the elements from a stream and the count of elements will be determined at runtime.
The fact, that it returns the elements in encounter order, makes it very useful for normal business usecases as well.
Happy Learning !!