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 红包祝福语简短10字
18 周六早晨祝福语简短