stream.limit() method in Java
Prerequisite : Streams in Java8
The limit(long N) is a method of java.util.stream.Stream object. This method takes one (long N) as an argument and returns a stream of size no more than N. limit() can be quite expensive on ordered parallel pipelines, if the value of N is large, because limit(N) is constrained to return the first N elements in the encounter order and not just any n elements.
Stream<T> limit(long N) Where N is the number of elements the stream should be limited to and this function returns new stream as output.
Exception : If the value of N is negative, then IllegalArgumentException is thrown by the function.
Below are some examples to understand the implementation of the function in a better way.
Example 1 :
New stream of length N after truncation is : -2 0 2 4
geeks for geeks
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.