LongStream limit() method in Java

Java 8Object Oriented ProgrammingProgramming

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
raja
Published on 27-Mar-2019 10:57:31
Advertisements