DEV Community

realNameHidden
realNameHidden

Posted on

Java 8 Stream API limit() and skip() methods

In Java 8, the Stream API provides limit() and skip() methods for controlling the number of elements in a stream.

limit(n): Limits the stream to the first n elements.

skip(n): Skips the first n elements and processes the rest.

Here’s an example demonstrating both:

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class StreamLimitSkipExample {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

        // Using limit() to get the first 5 elements
        List<Integer> limitedList = numbers.stream()
                .limit(5)
                .collect(Collectors.toList());
        System.out.println("First 5 elements: " + limitedList);

        // Using skip() to skip the first 5 elements and get the rest
        List<Integer> skippedList = numbers.stream()
                .skip(5)
                .collect(Collectors.toList());
        System.out.println("After skipping first 5 elements: " + skippedList);

        // Combining skip() and limit() to get elements from 4th to 7th positions
        List<Integer> limitedAndSkippedList = numbers.stream()
                .skip(3)     // skip first 3 elements (index starts at 0)
                .limit(4)    // then take the next 4 elements
                .collect(Collectors.toList());
        System.out.println("Elements from 4th to 7th positions: " + limitedAndSkippedList);
    }
}

Enter fullscreen mode Exit fullscreen mode

Explanation:

Using limit(5): This limits the stream to the first 5 elements, resulting in [1, 2, 3, 4, 5].

Using skip(5): This skips the first 5 elements and collects the rest, resulting in [6, 7, 8, 9, 10].

Combining skip(3) and limit(4): First, it skips the first 3 elements, then limits to the next 4, resulting in elements from positions 4 to 7: [4, 5, 6, 7].

Output:

First 5 elements: [1, 2, 3, 4, 5]
After skipping first 5 elements: [6, 7, 8, 9, 10]
Elements from 4th to 7th positions: [4, 5, 6, 7]

Enter fullscreen mode Exit fullscreen mode

This approach is useful for handling pagination or extracting specific ranges in a collection.

Top comments (0)