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


Java LongStream average()用法及代码示例


Java 8中的java.util.stream.LongStream处理原始Longs。它有助于解决旧问题,例如以新的方式在数组中找到最大值,在数组中找到最小值,数组中所有元素的总和以及数组中所有值的平均值。 LongStream average()返回一个OptionalDouble,描述此流的元素的算术平均值;如果此流为空,则返回一个空的Optional。
用法:

OptionalDouble average()

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

下面给出一些示例,以更好地理解该函数。
示例1:

// Java code for LongStream average() 
import java.util.*; 
import java.util.stream.LongStream; 
  
class GFG { 
  
    // Driver code 
    public static void main(String[] args) 
    { 
        // creating a stream 
        LongStream stream = LongStream.of(2L, 3L, 4L, 
                                          5L, 6L, 7L, 8L); 
  
        // OptionalDouble is a container object 
        // which may or may not contain a 
        // doouble 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"); 
        } 
    } 
}
输出:
5.0

示例2:

// Implementation of LongStream average() 
import java.util.*; 
import java.util.stream.LongStream; 
  
class GFG { 
  
    // Driver code 
    public static void main(String[] args) 
    { 
        // creating a stream 
        LongStream stream = LongStream.of(2L, 3L, 3L, 4L, 6L, 8L, 8L); 
  
        // OptionalDouble is a container object 
        // which may or may not contain a 
        // doouble 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.857142857142857


相关用法


注:本文由纯净天空筛选整理自Sahil_Bansall大神的英文原创作品 LongStream average() in Java with Examples。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。