In Java Stream API limit(long maxSize) method is used to truncate the stream so that it is not longer than maxSize in length and the method returns a stream consisting of that many elements of this stream.
Java Stream limit() method
Syntax of the limit method is as given below-
Stream<T> limit(long maxSize)
Here maxSize argument represents the number of elements the stream should be limited to.
If maxSize is negative then IllegalArgumentException is thrown otherwise a new Stream is returned which is no longer than maxSize in length.
Notes about limit() method
- limit() is generally considered a cheap operation on sequential stream pipelines
 - limit() can be quite expensive on ordered parallel pipelines, since limit(n) is constrained to return not just any n elements, but the first n elements in the encounter order.
 - It is a short-circuiting stateful intermediate operation. Since limit() method returns a new stream that makes it a stateful intermediate operation. An intermediate operation is short-circuiting if, when presented with infinite input, it may produce a finite stream as a result.
 
limit() Java examples
1. Getting a sublist from a List by limiting the number of elements to the first n elements of the original list.
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class StreamLimit {
  public static void main(String[] args) {
    StreamLimit sl = new StreamLimit();
    List<Integer> numList = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
    List<Integer> subList = numList.stream().limit(5).collect(Collectors.toList());     
    System.out.println("Sublist after limiting elements- " + subList);
  }
}
Output
Sublist after limiting elements- [1, 2, 3, 4, 5]
2. Getting 10 random numbers by using limit() with generate() method.
public class StreamLimit {
  public static void main(String[] args) {
    Stream.generate(Math::random)
          .map(n -> (int)(n * 100))
          .limit(10)
          .forEach(System.out::println);
  }
}
That's all for this topic Java Stream - limit() With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!
>>>Return to Java Advanced Tutorial Page
Related Topics
You may also like-
No comments:
Post a Comment