Java 中 IntStream 的 average() 方法
Java 中 IntStream 類的平均數() 函式返回一個 OptionalDouble,該函式描述了此流中元素的算術平均值,如果此流為空,則返回一個空選項。它獲取流中元素的平均值。
語法如下
OptionalDouble average()
此處,OptionalDouble 是一個可能包含或不包含雙精度值的容器物件。
使用一些元素建立 IntStream
IntStream intStream = IntStream.of(15, 13, 45, 18, 89, 70, 76, 56);
現在,獲取流中元素的平均值
OptionalDouble res = intStream.average();
以下是一個在 Java 中實現 IntStream average() 函式的示例。OptionalDouble 類的 isPresent() 函式如果存在值則返回 true
示例
import java.util.*; import java.util.stream.IntStream; public class Demo { public static void main(String[] args) { IntStream intStream = IntStream.of(15, 13, 45, 18, 89, 70, 76, 56); OptionalDouble res = intStream.average(); System.out.println("Average of the elements of the stream..."); if (res.isPresent()) { System.out.println(res.getAsDouble()); } else { System.out.println("Nothing!"); } } }
輸出
Average of the elements of the stream... 47.75
廣告