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:
// 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
// doouble 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:
// 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
// doouble 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
相關用法
- Java LongStream max()用法及代碼示例
- Java LongStream min()用法及代碼示例
- Java LongStream allMatch()用法及代碼示例
- Java LongStream anyMatch()用法及代碼示例
- Java LongStream noneMatch()用法及代碼示例
- Java LongStream distinct()用法及代碼示例
- Java LongStream filter()用法及代碼示例
- Java LongStream mapToInt()用法及代碼示例
- Java LongStream empty()用法及代碼示例
- Java LongStream peek()用法及代碼示例
- Java LongStream count()用法及代碼示例
- Java LongStream reduce(long identity, LongBinaryOperator op)用法及代碼示例
- Java IntStream average()用法及代碼示例
- Java DoubleStream average()用法及代碼示例
注:本文由純淨天空篩選整理自Sahil_Bansall大神的英文原創作品 LongStream average() in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。