DoubleStream limit() method in Java

Java 8Object Oriented ProgrammingProgramming

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

The syntax is as follows

DoubleStream limit(long max)

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

To use the DoubleStream class in Java, import the following package

import java.util.stream.DoubleStream;

Create a DoubleStream and add elements

DoubleStream doubleStream = DoubleStream.of(10.8, 20.7, 25.8, 35.7, 78.2, 89.7, 67.8, 86.3);

Now, to display n number of elements, set it as a parameter value for limit()

doubleStream.limit(5)

The following is an example to implement DoubleStream limit() method in Java

Example

 Live Demo

import java.util.*;
import java.util.stream.DoubleStream;
public class Demo {
   public static void main(String[] args) {
      DoubleStream doubleStream = DoubleStream.of(10.8, 20.7, 25.8, 35.7, 78.2, 89.7, 67.8, 86.3);
      // limits is 5 therefore only 5 elements would be visible
      doubleStream.limit(5).forEach(System.out::println);
   }
}

Here is the output. The limit is set to 5, therefore only 5 elements would be visible

Output

10.8
20.7
25.8
35.7
78.2
raja
Published on 28-Mar-2019 08:14:24
Advertisements