How do I use limit method in Java Stream API?

The limit(long maxSize) method in Java’s Stream API is used for reducing the size of the stream. It takes a single parameter, maxSize, which is a long value that represents the maximum number of elements that the stream should be limited to.

The primary purpose and usefulness of the limit() method can be summarized as follows:

  1. Short-circuit Operation: It provides a way to work with infinite streams. Even if your stream is infinite, using limit() allows you to get a finite number of elements.
  2. Performance Enhancement: Since limit() short-circuits the stream, it can significantly improve performance by reducing the number of operations performed, especially in large streams.

  3. Control Stream Size: The limit() method allows you to reduce the number of elements in the stream according to your needs without changing the original data source.

Here is a simple example of how to use it:

package org.kodejava.stream;

import java.util.stream.*;

public class StreamLimit {
    public static void main(String[] args) {
        Stream<Integer> numbersStream = Stream.of(1, 2, 3, 4, 5, 6, 7, 8, 9);
        numbersStream
                .limit(4)
                .forEach(System.out::println);
    }
}

Output:

1
2
3
4

In this code, we have a stream of nine numbers, but we are limiting this stream to just the first four elements, so only the numbers 1 to 4 are displayed on the console.

Please note that if the size of this stream is smaller than the maxSize then the same amount of stream will be returned. If the size of the stream is greater than the maxSize then the size of the stream will be maxSize.

Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.