In this tutorial, we will see “What is a Limit() method in Java 8 Stream and how we can use it?” limit stream java 8
Limit() method in Java Stream...!!! Click To Tweet
Streams Limit() Method
Syntax & Description
Returns a stream consisting of the elements of this stream, truncated to be no longer than maxSize
in length. It takes a single argument, an long n
, which represents the maximum number of elements the stream should contain.
This is a short-circuiting stateful intermediate operation.
Syntax: Stream<T> limit(long n)
How to use it – an Example?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | /** * Using Limit method as name suggest, Limit the stream to first 5 integers and print them * @author Deepak Verma * */ import java.util.Arrays; import java.util.List; import java.util.stream.Stream; public class Limit_Java8Stream_Example { public static void main(String args[]) { List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); // Get a stream of the numbers Stream<Integer> stream = numbers.stream(); // Limit the stream to the first 5 elements and print them stream.limit(5).forEach(System.out::println); } } |
Output:
1 2 3 4 5 | 1 2 3 4 5 |
limit stream java 8
skip method java 8 stream
Java 8 – Stream Limit() method with Example Click To Tweet
Do you like this Post? – then check my other helpful posts:
- Convert a Stream to a List in Java 8
- Stream maptoint in Java 8 with examples
- Double the numbers of specified ArrayList using Streams
- Double the even / odd numbers of a specified ArrayList using Streams
- How to check if Number is Prime or not using Streams
- Retrieve Even/Odd Numbers within the Range using Java 8 Streams
- How to add/sum up the ArrayList integers using Java8 Streams
- Generate Prime Numbers in Java 8 using Streams
- Comparator example – Collections sort with/without Lambda in Java 8
- How to pass function as a parameter in a method in Java 8?
- Remove duplicates from ArrayList in Java 8
- ForEach examples for Map/List in Java 8
Other Useful References: