Java中的 DoubleStream average() 示例
Java 8 中的Java .util.stream.DoubleStream处理原始双精度。它有助于以一种新的方式解决数组中的最大值,数组中的最小值,数组中所有元素的总和以及数组中所有值的平均值等老问题。 DoubleStream average()返回一个 OptionalDouble 描述此流的元素的算术平均值,如果此流为空,则返回一个空的可选项。如果任何记录的值是 NaN 或总和在任何点都是 NaN,则平均值将为 NaN。
句法 :
OptionalDouble average()
Where, OptionalDouble is a container object
which may or may not contain a double value.
注意:返回的平均值可能因记录值的顺序而异。通过增加绝对量级排序的元素往往会产生更准确的结果。
示例 1:
// Java code for DoubleStream average()
import java.util.*;
import java.util.stream.DoubleStream;
class GFG {
// Driver code
public static void main(String[] args)
{
// creating a stream
DoubleStream stream = DoubleStream.of(2.5, 3.6, 4.7, 5.0, 6.2);
// OptionalDouble is a container object
// which may or may not contain a
// double value.
OptionalDouble obj = stream.average();
// If a value is present, isPresent() will
// return true and getAsDouble() will
// return the value
if (obj.isPresent()) {
System.out.println(obj.getAsDouble());
}
else {
System.out.println("-1");
}
}
}
输出:
4.4
示例 2:
// Java code for DoubleStream average()
import java.util.*;
import java.util.stream.DoubleStream;
class GFG {
// Driver code
public static void main(String[] args)
{
// OptionalDouble is a container object
// which may or may not contain a
// double value.
OptionalDouble obj = DoubleStream.empty().average();
// If a value is present, isPresent() will
// return true and getAsDouble() will
// return the value
if (obj.isPresent()) {
System.out.println(obj.getAsDouble());
}
else {
System.out.println("-1");
}
}
}
输出:
-1
示例 3:
// Java code for DoubleStream average()
import java.util.*;
import java.util.stream.DoubleStream;
class GFG {
// Driver code
public static void main(String[] args)
{
// creating a stream
DoubleStream stream = DoubleStream.of(2.5, 3.6, 4.7,
Double.MAX_VALUE, Double.MAX_VALUE);
// OptionalDouble is a container object
// which may or may not contain a
// double value.
OptionalDouble obj = stream.average();
// If a value is present, isPresent() will
// return true and getAsDouble() will
// return the value
if (obj.isPresent()) {
System.out.println(obj.getAsDouble());
}
else {
System.out.println("-1");
}
}
}
输出:
Infinity