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


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


java.util.stream.DoubleStream在Java 8中,處理原始雙打。它有助於解決舊問題,例如以新的方式在數組中找到最大值,在數組中找到最小值,數組中所有元素的總和以及數組中所有值的平均值。 DoubleStream average()返回一個OptionalDouble,描述此流的元素的算術平均值;如果此流為空,則返回一個空的optional。如果任何記錄的值為NaN或總和在任何時候均為NaN,則平均值將為NaN。
用法:

OptionalDouble average()

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

注意:返回的平均值可能會有所不同,具體取決於記錄值的順序。通過增加絕對量排序的元素傾向於產生更準確的結果。

示例1:


// Java code for DoubleStream average() 
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(2.5, 3.6, 4.7, 5.0, 6.2); 
  
        // OptionalDouble is a container object 
        // which may or may not contain a 
        // double value. 
        OptionalDouble obj = stream.average(); 
  
        // 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"); 
        } 
    } 
}
輸出:
4.4

示例2:

// Java code for DoubleStream average() 
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().average(); 
  
        // 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

示例3:

// Java code for DoubleStream average() 
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(2.5, 3.6, 4.7, 
                                              Double.MAX_VALUE, Double.MAX_VALUE); 
  
        // OptionalDouble is a container object 
        // which may or may not contain a 
        // double value. 
        OptionalDouble obj = stream.average(); 
  
        // 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"); 
        } 
    } 
}
輸出:
Infinity


相關用法


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