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 妈妈生日祝福语简短励志