Thursday, September 30, 2021

Java Stream - limit() With Examples

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

  1. Java Stream - skip() With Examples
  2. Primitive Type Streams in Java Stream API
  3. Reduction Operations in Java Stream API
  4. Spliterator in Java
  5. Java Stream API Interview Questions And Answers

You may also like-

  1. Just In Time Compiler (JIT) in Java
  2. Byte Streams in Java IO
  3. How to Get The Inserted ID (Generated ID) in JDBC
  4. Method Reference in Java
  5. java.lang.ClassCastException - Resolving ClassCastException in Java
  6. Creating PDF in Java Using Apache PDFBox
  7. Method Overloading in Python
  8. Spring Boot Spring Initializr

No comments:

Post a Comment