Java Stream limit() Example

The Java Stream limit() method is an intermediate operation. 

The Java Stream limit() method can limit the number of elements in a stream to a number given to the limit() method as a parameter. The limit() method returns a new Stream that will at most contain the given number of elements. 

Java Stream limit() Example

Here is a Java Stream limit() example:

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Stream;

public class Main {
    public static void main(String[] args)
    {
        List<String> stringList = new ArrayList<>();

        stringList.add("one");
        stringList.add("two");
        stringList.add("three");
        stringList.add("one");

        Stream<String> stream = stringList.stream();

        stream.limit(2)
                .forEach( element -> { System.out.println(element); });
    }
}

Output:

one
two

Java Stream Methods/APIs Examples

Free Spring Boot Tutorial - 5 Hours Full Course


Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course

Comments