Java Stream limit() Method Tutorial

In this section, we will learn what the Stream limit() method is and how to use it in Java.

What is Java Stream limit() Method?

The Java Stream limit() method is used to set a limit on the number of elements that are coming from a stream.

For example, if you set the value 100 as the argument of this method, that means only the first 100 elements of the target stream will be processed. After that, the stream will end.

Java limit() Method Syntax:

Stream<T> limit(long maxSize)

limit() Method Parameters:

The method takes one argument and that is the maximum number of elements that are allowed to come from the target stream.

limit() Method Return Value:

The return value of this method is a new stream.

limit() Method Exceptions:

The method might throw one exception and that is:

IllegalArgumentException: we get this exception if the declared argument is a negative value.

Example: using Stream limit() method

import java.util.stream.Stream;
class Main{
    public static void main(String[] args) {
        Stream<Integer> stream = Stream.of(20,2,3,4,5,6,7,8,9,10,3,23,4,23,423,2,34,56,2,7,86,54,5);
        
        stream.limit(5).forEach(e->System.out.println(e));
    }
}

Output:

20

2

3

4

5

As you can see, because the value of the limit() method is set to 5, only the first 5 elements of the stream were processed and after that the stream ends.

Facebook
Twitter
Pinterest
LinkedIn

Top Technologies