Java 8 中收集器 averagingInt() 方法


Collectors 類的 averagingInt() 方法返回一個收集器,該收集器生成應用於輸入元素的 int 值函式的算術平均值。

語法如下 -

static <T> Collector<T,?,Double> averagingInt(ToIntFunction<? super T> mapper)

此處,引數 -

  • T - 輸入元素的型別

  • mapper - 提取要相加的屬性的函式

  • Double - 它將原始型別 double 的值包裝在一個物件中。

  • ToIntFunction - 生成 int 值結果的函式。

要在 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.averagingInt(a -> Integer.parseInt(a)));
      System.out.println("Arithmetic Mean of the stream elements = "+res);
   }
}

輸出

Arithmetic Mean of the stream elements = 99.16666666666667

更新日期: 2019 年 7 月 30 日

860 次瀏覽

開啟您的職業生涯

完成該課程即可獲得認證

立即開始
廣告
© . All rights reserved.