Java 中 IntStream 的 average() 方法
Java 中 IntStream 类的平均数() 函数返回一个 OptionalDouble,该函数描述了此流中元素的算术平均值,如果此流为空,则返回一个空选项。它获取流中元素的平均值。
语法如下
OptionalDouble average()
此处,OptionalDouble 是一个可能包含或不包含双精度值的容器对象。
使用一些元素创建 IntStream
IntStream intStream = IntStream.of(15, 13, 45, 18, 89, 70, 76, 56);
现在,获取流中元素的平均值
OptionalDouble res = intStream.average();
以下是一个在 Java 中实现 IntStream average() 函数的示例。OptionalDouble 类的 isPresent() 函数如果存在值则返回 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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP