Java中的IntStream average()方法
average()Java中IntStream类的方法返回描述此流元素算术平均值的OptionalDouble;如果此流为空,则返回一个空的optional。它获取流元素的平均值。
语法如下
OptionalDouble average()
在这里,OptionalDouble是一个容器对象,可能包含也可能不包含double值。
使用一些元素创建一个IntStream
IntStream intStream = IntStream.of(15, 13, 45, 18, 89, 70, 76, 56);
现在,获取流中元素的平均值
OptionalDouble res = intStream.average();
以下是average()在Java中实现IntStream方法的示例。isPresent()如果存在该值,则OptionalDouble类的方法返回true
示例
import java.util.*;
import java.util.stream.IntStream;
public class Demo {
public static void main(String[] args) {
IntStream intStream = IntStream.of(15, 13, 45, 18, 89, 70, 76, 56);
OptionalDouble res = intStream.average();
System.out.println("Average of the elements of the stream...");
if (res.isPresent()) {
System.out.println(res.getAsDouble());
} else {
System.out.println("Nothing!");
}
}
}输出结果
Average of the elements of the stream... 47.75
热门推荐
10 老公生日祝福语简短好看
11 新年简短的英文祝福语
12 姐妹结婚红包简短祝福语
13 生日祝福语简短独特格式
14 朋友明天手术祝福语简短
15 发给女儿生日简短祝福语
16 贺卡祝福语情侣搞笑简短
17 婚礼亲友祝福语简短幽默
18 猪年给老师祝福语简短