Skip to content
Related Articles

Related Articles

Improve Article
DoubleStream max() in Java with examples
  • Difficulty Level : Easy
  • Last Updated : 06 Dec, 2018

java.util.stream.DoubleStream in Java 8, deals with primitive doubles. It helps to solve the problems like finding maximum value in array, finding minimum value in array, sum of all elements in array, and average of all values in array in a new way. DoubleStream max() returns an OptionalDouble describing the maximum element of this stream, or an empty optional if this stream is empty.

Syntax :

OptionalDouble() max()

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

Note :

  1. Unlike the numerical comparison operators, this method considers negative zero to be strictly smaller than positive zero.
  2. This is a special case of a reduction.

Example 1 :




// Java code for DoubleStream max()
import java.util.*;
import java.util.stream.DoubleStream;
  
class GFG {
  
    // Driver code
    public static void main(String[] args)
    {
        // creating a stream
        DoubleStream stream = DoubleStream.of(-9.5, -18.6, 54.3,
                                            8.5, 7.4, 14.2, 3.9);
  
        // OptionalDouble is a container object
        // which may or may not contain a
        // double value.
        OptionalDouble obj = stream.max();
  
        // If a value is present, isPresent() will
        // return true and getAsDouble() will
        // return the value
        if (obj.isPresent()) {
            System.out.println(obj.getAsDouble());
        }
        else {
            System.out.println("-1");
        }
    }
}
Output:



54.3

Example 2 :




// Java code for DoubleStream max()
import java.util.*;
import java.util.stream.DoubleStream;
  
class GFG {
  
    // Driver code
    public static void main(String[] args)
    {
        // OptionalDouble is a container object
        // which may or may not contain a
        // double value.
        OptionalDouble obj = DoubleStream.empty()
                                 .max();
  
        // If a value is present, isPresent() will
        // return true and getAsDouble() will
        // return the value
        if (obj.isPresent()) {
            System.out.println(obj.getAsDouble());
        }
        else {
            System.out.println("-1");
        }
    }
}
Output:
-1

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :