LongStream limit() method in Java


The limit() method of the LongStream class in Java returns a stream consisting of the elements of this stream, truncated to be no longer than max in length. Here, max is the parameter of the method.

The syntax is as follows.

LongStream limit(long max)

Here, max is the number of elements the stream should be limited to.

To use the LongStream class in Java, import the following package.

import java.util.stream.LongStream;

Create a LongStream and add elements.

LongStream longStream = LongStream.of(2000L, 35000L, 45000L, 50500L, 65000L, 72000L);

Now, let’s say you only want to return 4 elements. For that, use the limit as 4.

longStream.limit(4).

The following is an example to implement LongStream limit() method.

Example

 Live Demo

import java.util.stream.LongStream;
public class Demo {
   public static void main(String[] args) {
      LongStream longStream = LongStream.of(2000L, 35000L, 45000L, 50500L, 65000L, 72000L);
      System.out.println("Remaining elements of the stream...");
      longStream.limit(4).forEach(System.out::println);
   }
}

Output

Remaining elements of the stream...
2000
35000
45000
50500

Updated on: 30-Jul-2019

38 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements