average()Java中DoubleStream类的方法返回OptionalDouble,这是此流的元素的算术平均值。如果流为空,则返回空。
语法如下:
OptionalDouble average()
在这里,OptionalDouble是一个容器对象,可能包含也可能不包含double值。
要在Java中使用DoubleStream类,请导入以下软件包:
import java.util.stream.DoubleStream;
首先,创建DoubleStream并添加一些元素:
DoubleStream doubleStream = DoubleStream.of(50.8, 35.7, 49.5,12.7, 89.7, 97.4);
获取流元素的平均值:
OptionalDouble res = doubleStream.average();
以下是average()在Java中实现DoubleStream方法的示例:
import java.util.*;
import java.util.stream.DoubleStream;
public class Demo {
public static void main(String[] args) {
DoubleStream doubleStream = DoubleStream.of(50.8, 35.7, 49.5,12.7, 89.7, 97.4);
OptionalDouble res = doubleStream.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... 55.96666666666667
让我们看另一个例子:
import java.util.*;
import java.util.stream.DoubleStream;
public class Demo {
public static void main(String[] args) {
DoubleStream doubleStream = DoubleStream.empty();
OptionalDouble res = doubleStream.average();
if (res.isPresent()) {
System.out.println(res.getAsDouble());
} else {
System.out.println("Nothing! Stream is empty!");
}
}
}以下是输出,因为流为空,因此不显示任何内容:
输出结果
Nothing! Stream is empty!