DEV Community

realNameHidden
realNameHidden

Posted on

3 1 1 1 1

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.

Image of Quadratic

Free AI chart generator

Upload data, describe your vision, and get Python-powered, AI-generated charts instantly.

Try Quadratic free

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay