Java 8 Collectors averagingDouble() 方法


Java 8 Collectors 類的 averagingDouble() 方法返回算術平均值,該平均值基於輸入元素應用的雙精度值函式。

語法如下 −

public static <T> Collector<T,?,Double> averagingDouble(ToDoubleFunction<? super T> mapper)

其中,引數 −

  • T - 輸入元素的型別

  • mapper - 提取要求和的屬性的函式

  • Double - 用一個物件包裝原始 double 型別的一個值。

  • ToDoubleFunction - 產生 double 值結果的函式。

要使用 Java 中的 Collectors 類,匯入以下包 −

import java.util.stream.Collectors;

下面是一個在 Java 中實現 averagingDouble() 方法的示例 −

示例

 線上演示

import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Demo {
   public static void main(String[] args) {
      Stream<String> stream = Stream.of("20", "50", "75", "100", "150", "200");
      double res = stream.collect(Collectors.averagingDouble(a -> Double.parseDouble(a)));
      System.out.println("Arithmetic Mean of the stream elements = "+res);
   }
}

輸出

Arithmetic Mean of the stream elements = 99.16666666666667

更新於: 2019-07-30

433 檢視次數

開啟你的 職業

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.