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:
- 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. -
Performance Enhancement: Since
limit()
short-circuits the stream, it can significantly improve performance by reducing the number of operations performed, especially in large streams. -
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
.
- How do I create a servlet filter to make secure cookies? - April 18, 2024
- How do I configure secure cookies using web.xml? - April 18, 2024
- How do I create a table with multiple header in iText 8? - March 16, 2024