Home > Java > javaTutorial > Java tream API limit() and skip() methods

Java tream API limit() and skip() methods

Susan Sarandon
Release: 2024-11-03 08:42:02
Original
309 people have browsed it

Java tream 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);
    }
}

Copy after login

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]

Copy after login

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

The above is the detailed content of Java tream API limit() and skip() methods. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template