Java Stream limit() Example

1. Introduction

The limit() method in Java Streams is an intermediate operation that truncates the stream to a given size. This method is particularly useful when you want to process or retrieve only a certain number of elements from a potentially large or infinite stream. It's commonly used in scenarios where performance and efficiency are critical, such as processing large datasets or handling paging and batching operations.

Key Points

1. limit() helps control the size of the stream by specifying the maximum number of elements it should consist of.

2. It is a non-terminal operation and will only be executed when a terminal operation is triggered.

3. This method is particularly beneficial for performance optimization, especially when working with large or infinite streams.

2. Program Steps

1. Import necessary classes.

2. Create a stream of elements.

3. Apply the limit() method to restrict the number of elements.

4. Use a terminal operation to output the results.

3. Code Program

import java.util.stream.Stream;

public class StreamLimitExample {

    public static void main(String[] args) {
        // Step 2: Create a stream of elements
        Stream<Integer> infiniteNumbers = Stream.iterate(1, n -> n + 1);

        // Step 3: Apply limit() to truncate the stream
        Stream<Integer> limitedNumbers = infiniteNumbers.limit(5);

        // Step 4: Use forEach to output the results
        System.out.println("Limited numbers:");
        limitedNumbers.forEach(System.out::println);
    }
}

Output:

Limited numbers:
1
2
3
4
5

Explanation:

1. Stream Creation: A stream of infinite numbers is created using Stream.iterate(), starting from 1 and incrementing by 1 for each subsequent element. This kind of stream can potentially run indefinitely.

2. Applying limit(): The limit(5) method is used to truncate this infinite stream to the first 5 elements. This operation is crucial for making the stream manageable and preventing it from processing more elements than necessary.

3. Terminal Operation: The forEach() method is then used to consume the stream and output each of the limited elements. It acts as a terminal operation that triggers the execution of the stream pipeline.

4. Utility and Benefits: Using limit() in this context demonstrates its effectiveness in controlling the volume of data processed, which is essential for optimizing performance and resource usage, especially in applications dealing with large data sets or requiring pagination.


Comments