Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

limit
java
stream
communitycreator

What is the limit() method of Stream Interface?

Programming Bytes

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

When we call limit(N), we will get a new Stream with the first N elements of this Stream in the encounter orderThe order in which the elements of the stream are supplied..

For example, consider that we have a stream of ten elements and we called limit(5) on the stream. Then, a new stream with the first five elements of the original stream will be returned.

Syntax

Stream<T> limit(long N)
  • N: The number of elements the stream should be limited to.

  • The limit(N) method will return the first N elements in the encounter order of the Stream.

  • The limit(N) is a cheap operation on sequential stream pipelines.

  • In the ordered parallel stream, the limit method may be expensive if the value of N is large because the stream is processed in a parallel manner by different threads. This performance issue can be avoided by using the unordered stream, removing the ordering constraint with BaseStream.unordered(), or using a sequential stream instead of a parallel stream.

  • IllegalArgumentException is thrown if we pass negative numbers as the value for N.

Example

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
class LimitExample {
public static void main(String[] args)
{
Stream<Integer> numbers = Stream.of(1, 2, 3, 4, 5);
List<Integer> newList = numbers
.limit(3)
.collect(Collectors.toList());
System.out.println(newList);
}
}

In the above code:

  • We created a Stream of numbers with the name numbers, with the values:
1,2,3,4,5
  • We called the limit(3) method on the numbers stream. The limit(3) will return a new stream with the first three elements from the original stream.

  • Using the collect (Collectors.toList()) method, we were able to collect the stream as a List.

RELATED TAGS

limit
java
stream
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring