DoubleStream max() method in Java


The max() method of the DoubleStream class returns an OptionalDouble describing the maximum element of this stream, or an empty OptionalDouble if this stream is empty.

The syntax is as follows.

OptionalDouble max()

Here, OptionalDouble is a container object which may or may not contain a double value.

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

import java.util.stream.DoubleStream;

Create a DoubleStream and add some elements.

DoubleStream doubleStream = DoubleStream.of(67.9, 89.9, 10.5, 95.8, 49.6);

Now, get the maximum element from the stream.

OptionalDouble res = doubleStream.max();

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

Example

 Live Demo

import java.util.OptionalDouble;
import java.util.stream.DoubleStream;
public class Demo {
   public static void main(String[] args) {
      DoubleStream doubleStream = DoubleStream.of(67.9, 89.9, 10.5, 95.8, 49.6);
      OptionalDouble res = doubleStream.max();
      System.out.println("Maximum element: ");
      if (res.isPresent()) {
         System.out.println(res.getAsDouble());
      } else {
         System.out.println("Nothing!");
      }
   }
}

Output

Maximum element:
95.8

Updated on: 30-Jul-2019

152 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements