Java Stream limit() Method with Examples

limit(long maxSize) method in the Java Stream API truncates the stream so that it is no longer than maxSize in length and returns the new stream with limited elements.

limit method in Java Stream

Syntax of the method is as given below.

Stream<T> limit(long maxSize)

Here maxSize is the limit on the number of elements stream should be truncated to. If you pass maxSize as negative then IllegalArgumentException is thrown.

Points about limit method

  1. It is a short-circuiting stateful intermediate operation which means it will return a new Stream. An intermediate operation is short-circuiting if, when presented with infinite input, it may produce a finite stream as a result.
  2. limit() is generally a cheap operation on sequential stream pipelines.
  3. limit() can be quite expensive on ordered parallel pipelines, if n is a fairly large values, because of the constraint to skip first n elements in the encounter order.

limit() Java Example

1. In the following example we’ll generate 10 random numbers. Initially generate() method of the java.util.stream is called to create an infinite Stream which generates random numbers of type double. Using map operation of Stream API these random numbers are then transformed to type int and having two digits. limit() method is then used to limit the stream to 10 elements.

import java.util.stream.Stream;

public class LimitDemo {
  public static void main(String[] args) {
    Stream.generate(Math::random).map(n -> (int)(n * 100)).limit(10).forEach(System.out::println);
  }
}

Output

16
64
17
97
18
5
16
74
50
87

2. In this example we’ll try to get a sublist from a List using limit() method to truncate the original list. Method getSubList() is a generic method that can work with any type of List, second argument passed to the method is the number of elements list should be limited to. Results of the stream returned by limit() method are collected to a list and that new list is returned.

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

public class LimitDemo {
  public static void main(String[] args) {
    LimitDemo ld = new LimitDemo();
    // Used with list of Strings
    List<String> cityList = Arrays.asList("Delhi", "Mumbai", "London", "New York","Bengaluru");
    List<String> newList = ld.getSubList(cityList, 3);
    System.out.println("List after limiting elements- " + newList);
    // Used with list of Integers
    List<Integer> numList = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);
    List<Integer> tempList = ld.getSubList(numList, 6);
    System.out.println("List after limiting elements- " + tempList);
  }
  
  // This method uses skip method to skip n elements
  public <T> List<T> getSubList(List<T> originalList, long maxSize){
    return originalList.stream().limit(maxSize).collect(Collectors.toList());
  }
}

Output

List after limiting elements- [Delhi, Mumbai, London]
List after limiting elements- [1, 2, 3, 4, 5, 6]

Related Posts

That’s all for the topic Java Stream limit() Method with Examples. If something is missing or you have something to share about the topic please write a comment.


You may also like

Share this post:

Leave a Reply

Your email address will not be published. Required fields are marked *

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