Java 8中的java.util.stream.IntStream處理原始int。它有助於解決舊問題,例如以新的方式在數組中找到最大值,在數組中找到最小值,數組中所有元素的總和以及數組中所有值的平均值。 IntStream average()返回一個OptionalDouble,描述此流的元素的算術平均值;如果此流為空,則返回一個空的Optional。
用法:
OptionalDouble average() Where, OptionalDouble is a container object which may or may not contain a double value.
下麵給出一些示例,以更好地理解該函數。
示例1:
// Java code for IntStream average()
import java.util.*;
import java.util.stream.IntStream;
class GFG {
// Driver code
public static void main(String[] args)
{
// creating a stream
IntStream stream = IntStream.of(2, 3, 4, 5, 6, 7, 8);
// 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 IntStream average()
import java.util.*;
import java.util.stream.IntStream;
class GFG {
// Driver code
public static void main(String[] args)
{
// creating a stream
IntStream stream = IntStream.of(2, 3, 3, 4, 6, 8, 8);
// 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 IntStream min()用法及代碼示例
- Java IntStream max()用法及代碼示例
- Java IntStream noneMatch()用法及代碼示例
- Java IntStream empty()用法及代碼示例
- Java IntStream filter()用法及代碼示例
- Java IntStream anyMatch()用法及代碼示例
- Java IntStream allMatch()用法及代碼示例
- Java IntStream count()用法及代碼示例
- Java IntStream toArray()用法及代碼示例
- Java IntStream distinct()用法及代碼示例
- Java IntStream peek()用法及代碼示例
- Java IntStream.Builder build()用法及代碼示例
- Java IntStream codePoints()用法及代碼示例
- Java IntStream reduce(IntBinaryOperator op)用法及代碼示例
- Java IntStream reduce(int identity, IntBinaryOperator op)用法及代碼示例
注:本文由純淨天空篩選整理自Sahil_Bansall大神的英文原創作品 IntStream average() in Java with Examples。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。