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 生日开业蛋糕祝福语简短