Java Stream limit() Method

The limit() method in Java, part of the java.util.stream.Stream interface, is used to truncate a stream to a given length. This method is useful when you need to process only a specific number of elements from a stream.

Table of Contents

  1. Introduction
  2. limit() Method Syntax
  3. Understanding limit()
  4. Examples
    • Basic Usage
    • Using limit() with Filtered Streams
  5. Real-World Use Case
  6. Conclusion

Introduction

The limit() method returns a stream consisting of the elements of the original stream, truncated to be no longer than the specified size. This method is an intermediate operation, meaning it returns a new stream and does not modify the original stream.

limit() Method Syntax

The syntax for the limit() method is as follows:

Stream<T> limit(long maxSize)

Parameters:

  • maxSize: The number of elements the resulting stream should be limited to.

Returns:

  • A new Stream consisting of the elements of the original stream, truncated to the specified length.

Throws:

  • IllegalArgumentException: If maxSize is negative.

Understanding limit()

The limit() method allows you to limit the number of elements in a stream to a specified maximum size. This is particularly useful when you only need to process a subset of the elements in a stream.

Examples

Basic Usage

To demonstrate the basic usage of limit(), we will create a Stream and use limit() to truncate it to a specific number of elements.

Example

import java.util.stream.Stream;

public class LimitExample {
    public static void main(String[] args) {
        Stream<String> stream = Stream.of("apple", "banana", "cherry", "date", "elderberry");

        // Use limit() to truncate the stream to 3 elements
        Stream<String> limitedStream = stream.limit(3);

        // Print the limited elements
        limitedStream.forEach(System.out::println);
    }
}

Output:

apple
banana
cherry

Using limit() with Filtered Streams

This example shows how to use limit() in combination with other stream operations, such as filtering.

Example

import java.util.stream.Stream;

public class LimitWithFilterExample {
    public static void main(String[] args) {
        Stream<String> stream = Stream.of("apple", "banana", "cherry", "date", "elderberry");

        // Filter elements that start with 'a' or 'b', and limit the result to 2 elements
        Stream<String> limitedStream = stream.filter(s -> s.startsWith("a") || s.startsWith("b"))
                                             .limit(2);

        // Print the limited elements
        limitedStream.forEach(System.out::println);
    }
}

Output:

apple
banana

Real-World Use Case

Pagination

In real-world applications, the limit() method can be used to implement pagination by combining it with skip() to process specific pages of data.

Example

import java.util.stream.Stream;

public class PaginationExample {
    public static void main(String[] args) {
        Stream<String> stream = Stream.of("apple", "banana", "cherry", "date", "elderberry",
                                          "fig", "grape", "honeydew");

        int page = 2;
        int pageSize = 3;

        // Use skip() to skip the elements of previous pages, and limit() to get the elements of the current page
        Stream<String> pageStream = stream.skip((page - 1) * pageSize)
                                          .limit(pageSize);

        // Print the elements of the current page
        pageStream.forEach(System.out::println);
    }
}

Output:

date
elderberry
fig

Conclusion

The Stream.limit() method is used to truncate a stream to a specified maximum length. This method is particularly useful for scenarios where you need to process only a specific number of elements from a stream. By understanding and using this method, you can efficiently manage and process streams of values in your Java applications, ensuring that you work with only the required number of elements.

Comments