當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


Java DoubleStream max()用法及代碼示例


Java 8中的java.util.stream.DoubleStream處理原始雙精度型。它以新的方式幫助解決諸如在數組中找到最大值,在數組中找到最小值,數組中所有元素的總和以及數組中所有值的平均值之類的問題。 DoubleStream max()返回一個OptionalDouble,描述此流的最大元素,如果此流為空,則返回一個空的Optional。

用法:

OptionalDouble() max()

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

注意:


  1. 與數值比較運算符不同,此方法認為負零嚴格小於正零。
  2. 這是減少的特殊情況。

示例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"); 
        } 
    } 
}
輸出:
54.3

示例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"); 
        } 
    } 
}
輸出:
-1


相關用法


注:本文由純淨天空篩選整理自Sahil_Bansall大神的英文原創作品 DoubleStream max() in Java with examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。