Java中的 LongStream average() 示例
Java 8 中的Java .util.stream.LongStream 处理原始 Long。它有助于以一种新的方式解决数组中的最大值,数组中的最小值,数组中所有元素的总和以及数组中所有值的平均值等旧问题。 LongStream average()返回一个 OptionalDouble 描述此流的元素的算术平均值,如果此流为空,则返回一个空的可选项。
句法 :
OptionalDouble average()
Where, OptionalDouble is a container object
which may or may not contain a double value.
下面给出了一些示例,以更好地理解该函数。
示例 1:
Java
// Java code for LongStream average()
import java.util.*;
import java.util.stream.LongStream;
class GFG {
// Driver code
public static void main(String[] args)
{
// creating a stream
LongStream stream = LongStream.of(2L, 3L, 4L,
5L, 6L, 7L, 8L);
// 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");
}
}
}
Java
// Implementation of LongStream average()
import java.util.*;
import java.util.stream.LongStream;
class GFG {
// Driver code
public static void main(String[] args)
{
// creating a stream
LongStream stream = LongStream.of(2L, 3L, 3L, 4L, 6L, 8L, 8L);
// 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");
}
}
}
输出:
5.0
示例 2:
Java
// Implementation of LongStream average()
import java.util.*;
import java.util.stream.LongStream;
class GFG {
// Driver code
public static void main(String[] args)
{
// creating a stream
LongStream stream = LongStream.of(2L, 3L, 3L, 4L, 6L, 8L, 8L);
// 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.857142857142857