Stream limit() and skip() are intermediate operations in Java. The limit(n) method will limit the n numbers of elements to be processed in a stream. While the skip(n) method will skip the first n number from the stream.
Syntax of the limit() method
Stream<T> limit(long maxSize)
Stream<T> limit(long maxSize) limits a stream of T objects to a maximum size of maxSize. It returns a new Stream that contains only the first maxSize number of elements from the original stream.
Syntax of the skip() method
Stream<T> skip(long n)
The skip() method returns a stream consisting of the remaining elements after discarding the first n elements. If this stream contains fewer than n elements, we’ll get an empty stream.
Java Stream limit() and skip() operations – examples
Example 1
A program that takes a stream of integers and uses the limit() method to limit the list to the first 5 elements and apply the map() function to each element, which multiplies it by 2. The result is then collected in a new List:
class Test {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
List<Integer> resultList = numbers.stream()
.limit(5)
.map(num -> num * 2)
.collect(Collectors.toList());
System.out.println(resultList);
}
}
Output: [2, 4, 6, 8, 10]
Example 2
A program that takes a stream of integers and multiplies elements by 2 but skips the first 5 elements, using the skip() method:
class Test {
public static void main(String[] args) {
List<Integer> numbers = new ArrayList<>(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));
List<Integer> resultList = numbers.stream()
.skip(5)
.map(num -> num * 2)
.collect(Collectors.toList());
System.out.println(resultList);
}
}
Output: [12, 14, 16, 18, 20]
I hope this tutorial was helpful to you. To learn more, check out other Java Functional Programming tutorials.