Java 8中的java.util.stream.LongStream处理原始Longs。它有助于解决旧问题,例如以新的方式在数组中找到最大值,在数组中找到最小值,数组中所有元素的总和以及数组中所有值的平均值。 LongStream average()返回一个OptionalDouble,描述此流的元素的算术平均值;如果此流为空,则返回一个空的Optional。
用法:
OptionalDouble average()
Where, OptionalDouble is a container object
which may or may not contain a double value.
示例1:
import java.util.*;
import java.util.stream.LongStream;
class GFG {
public static void main(String[] args)
{
LongStream stream = LongStream.of(2L, 3L, 4L,5L, 6L, 7L, 8L);
OptionalDouble obj = stream.average();
if (obj.isPresent()) {
System.out.println(obj.getAsDouble());
}else {
System.out.println("-1");
}
}
}
输出:
5.0
示例2:
import java.util.*;
import java.util.stream.LongStream;
class GFG {
public static void main(String[] args)
{
LongStream stream = LongStream.of(2L, 3L, 4L,5L, 6L, 7L, 8L);
OptionalLong obj2 = stream.max();
if (obj2.isPresent()) {
System.out.println(obj2.getAsLong());
}else {
System.out.println("-1");
}
}
}
输出:
8
相关API:
|