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

更新時間:30-7-2019

11K+ 瀏覽

開啟你的 職業生涯

完成課程即可獲得認證

開始
廣告