Java Stream limit() Example

1. Introduction

This tutorial explores the limit() method of the Java Stream API. The limit() method truncates a stream to a specific size by limiting the number of elements the stream should consist of. It is particularly useful when you want to restrict the amount of data processed from potentially large datasets.

Key Points

1. limit() is an intermediate operation that reduces the size of the stream to the specified number of elements.

2. It is useful for processing a subset of data from a larger dataset or stream.

3. It can help in performance optimization by reducing the workload on subsequent stream operations.

2. Program Steps

1. Create a Stream of elements.

2. Apply the limit() method to reduce the size of the stream.

3. Collect or process the limited stream to demonstrate its effect.

3. Code Program

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class StreamLimitExample {

    public static void main(String[] args) {
        // Stream of integers
        Stream<Integer> numberStream = Stream.iterate(1, n -> n + 1);

        // Limiting the stream to the first 5 elements
        List<Integer> limitedNumbers = numberStream.limit(5).collect(Collectors.toList());
        System.out.println("Limited numbers: " + limitedNumbers);
    }
}

Output:

Limited numbers: [1, 2, 3, 4, 5]

Explanation:

1. Stream.iterate(1, n -> n + 1) creates an infinite stream of integers starting from 1 and incrementing by 1.

2. numberStream.limit(5) truncates the stream to the first 5 elements.

3. .collect(Collectors.toList()) collects the elements into a list, which is then printed to show the effect of limit().

Comments