What is the limit() method of Stream Interface?
When we call limit(N), we will get a new Stream with the first N elements of this Stream in the
For example, consider that we have a stream of ten elements and we called limit(5) on the stream. Then, a new stream with the first five elements of the original stream will be returned.
Syntax
Stream<T> limit(long N)
-
N: The number of elements the stream should be limited to. -
The
limit(N)method will return the firstNelements in the encounter order of theStream. -
The
limit(N)is a cheap operation on sequential stream pipelines. -
In the ordered parallel stream, the
limitmethod may be expensive if the value ofNis large because the stream is processed in a parallel manner by different threads. This performance issue can be avoided by using the unordered stream, removing the ordering constraint withBaseStream.unordered(), or using a sequential stream instead of a parallel stream. -
IllegalArgumentExceptionis thrown if we pass negative numbers as the value forN.
Example
import java.util.List;import java.util.stream.Collectors;import java.util.stream.Stream;class LimitExample {public static void main(String[] args){Stream<Integer> numbers = Stream.of(1, 2, 3, 4, 5);List<Integer> newList = numbers.limit(3).collect(Collectors.toList());System.out.println(newList);}}
In the above code:
- We created a
Streamof numbers with the namenumbers, with the values:
1,2,3,4,5
-
We called the
limit(3)method on thenumbersstream. Thelimit(3)will return a new stream with the first three elements from the original stream. -
Using the collect
(Collectors.toList())method, we were able to collect the stream as aList.