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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP