Java 8 FAQ: Top Questions
22. What is the purpose of limit() and skip() methods in Java 8 Streams?
The limit()
and skip()
methods are intermediate operations used to control the number of elements processed in a stream pipeline. limit(n)
restricts the stream to the first n
elements, while skip(n)
ignores the first n
elements.
πΊοΈ Step-by-Step Instructions:
- Use
limit(n)
to take only the firstn
elements. - Use
skip(n)
to discard the firstn
elements. - Both preserve the order of the stream and can be chained together.
π₯ Example Input:
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
π Using limit() and skip():
List<Integer> sublist = numbers.stream()
.skip(2)
.limit(4)
.collect(Collectors.toList());
β Java 8 Solution:
import java.util.*;
import java.util.stream.*;
public class LimitSkipExample {
public static void main(String[] args) {
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
List<Integer> sublist = numbers.stream()
.skip(2)
.limit(4)
.collect(Collectors.toList());
System.out.println(sublist);
}
}
π Output:
[3, 4, 5, 6]
π Detailed Explanation:
- limit(n): Truncates the stream after
n
elements. - skip(n): Discards the first
n
elements of the stream. - Useful for pagination, slicing, or sampling datasets.
π οΈ Use Cases:
- Paginating results in a web application.
- Fetching subsets of large collections.
- Skipping headers or pre-processing metadata in a stream.