Java 8中的java.util.stream.DoubleStream处理原始双精度型。它以新的方式帮助解决诸如在数组中找到最大值,在数组中找到最小值,数组中所有元素的总和以及数组中所有值的平均值之类的问题。 DoubleStream max()返回一个OptionalDouble,描述此流的最大元素,如果此流为空,则返回一个空的Optional。
用法:
OptionalDouble() max()
Where, OptionalDouble is a container object which
may or may not contain a double value.
注意:
与数值比较运算符不同,此方法认为负零严格小于正零。
这是减少的特殊情况。
示例1:
// Java code for DoubleStream max()
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(-9.5, -18.6, 54.3,
8.5, 7.4, 14.2, 3.9);
// OptionalDouble is a container object
// which may or may not contain a
// double value.
OptionalDouble obj = stream.max();
// 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");
}
}
}
输出:
54.3
示例2:
// Java code for DoubleStream max()
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()
.max();
// 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