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.