Swiftorial Logo
Home
Swift Lessons
Tutorials
Learn More
Career
Resources

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:

  1. Use limit(n) to take only the first n elements.
  2. Use skip(n) to discard the first n elements.
  3. 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.