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
廣告
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP