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.
Stream<T> limit(long N)
N
: The number of elements the stream should be limited to.
The limit(N)
method will return the first N
elements in the encounter order of the Stream
.
The limit(N)
is a cheap operation on sequential stream pipelines.
In the ordered parallel stream, the limit
method may be expensive if the value of N
is 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 with BaseStream.unordered()
, or using a sequential stream instead of a parallel stream.
IllegalArgumentException
is thrown if we pass negative numbers as the value for N
.
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:
Stream
of numbers with the name numbers
, with the values:1,2,3,4,5
We called the limit(3)
method on the numbers
stream. The limit(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 a List
.