当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。