Java 8 中的 Collectors averagingLong() 方法


Collectors 類的 averagingLong() 方法返回一個 Collector,該 Collector 會生成應用於輸入元素的長值函式的算術平均值。

語法如下

static <T> Collector<T,?,Double> averagingLong(ToLongFunction<? super T> mapper)

其中,引數

  • T - 輸入元素的型別
  • mapper - 提取要求和的屬性的函式
  • Double - 將基本型別 double 的值包裝在一個物件中。
  • ToLongFunction - 生成長值結果的函式。

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

import java.util.stream.Collectors;

以下是 Java 中實現 averagingLong() 方法的示例

示例

 線上演示

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.averagingLong(a -> Long.parseLong(a)));
      System.out.println("Arithmetic Mean of the stream elements = "+res);
   }
}

輸出

Arithmetic Mean of the stream elements = 99.16666666666667

更新於: 2019 年 7 月 30 日

259 次瀏覽

開啟你的 職業生涯

透過完成課程來獲得認證

開始
廣告
© . All rights reserved.