JAVAutil。流动Java 8中的IntStream处理原始Int。它以一种新的方式解决了数组中求最大值、求最小值、求数组中所有元素之和、求数组中所有值的平均等老问题。 IntStream average() 返回描述此流元素算术平均值的OptionalDouble,如果此流为空,则返回空可选值。
null
语法:
OptionalDouble average()Where, OptionalDouble is a container object which may or may not contain a double value.
下面给出了一些例子,以更好地理解函数。
例1:
JAVA
// 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 // 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 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 // 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
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END