在这篇博文中,我们将通过实例介绍LongSummaryStatistics。
LongSummaryStatistics是一个用于收集统计数据的类,在长数据上使用sum、max、min、average和count等操作。
Java.util包为整数数据提供了三个类IntSummaryStatistics,为双倍数据提供了DoubleSummaryStatistics,为长数据提供了LongSummaryStatistics。这些类与流和lambda表达式一起工作。
LongSummaryStatistics类接受方法示例
这提供了accept()方法来记录用于计算的值。
LongSummaryStatistics statsPrimitive = new LongSummaryStatistics();
statsPrimitive.accept(17);
statsPrimitive.accept(6);
statsPrimitive.accept(4);
statsPrimitive.accept(2);
statsPrimitive.accept(18);
statsPrimitive.accept(51);
System.out.println(statsPrimitive);
输出是
LongSummaryStatistics{count=6, sum=98, min=2, average=16.333333, max=51}
LongSummaryStatistics流数组示例
下面的例子 - 使用List.of()工厂静态方法创建了学生列表 给出对象流并将其映射到mapToLong方法,该方法需要toLongFunction- 一个接受对象并产生长输出的函数接口。最后,调用summaryStatistics()方法来返回对象。
import java.util.List;
import java.util.LongSummaryStatistics;
public class Summary2 {
public static void main(String[] args) {
List empLists = List.of(new Student(15000), new Student(2000), new Student(21000), new Student(2500));
LongSummaryStatistics sumaryStats = empLists.stream().mapToLong((value) -> value.getRank()).summaryStatistics();
System.out.println(sumaryStats);
}
}
class Student {
long rank;
public Student(long rank) {
super();
this.rank = rank;
}
public long getRank() {
return rank;
}
}
LongSummaryStatistics{count=4, sum=40500, min=2000, average=10125.000000, max=21000}
Collectors.summaryizingLong()是定义在java.util.stream包中的一个静态方法。
语法
Collector summarizingLong(ToLongFunction mapper)
List list = Arrays.asList(5l, 4l, 1l, 7l, 3l);
LongSummaryStatistics summaryStats = list.stream().collect(Collectors.summarizingLong(Long::longValue));
System.out.println(summaryStats);
输出是
LongSummaryStatistics{count=5, sum=20, min=1, average=4.000000, max=7}
上面的例子解释如下:
- 从一个数组创建一个列表。
- 使用stream()将列表转换成Stream,用Collectors.sumplizingLong参数将其收集起来,返回LongSummaryStatistics。
LongStream summaryStatistics()方法示例
LongStream是Long数据类型的一个流版本,它支持顺序和并行操作。summaryStatistics()方法返回LongSummaryStatistics,它包含长流数据的汇总统计。
LongStream longStream = LongStream.of(5, 4, 1, 7, 3);
LongSummaryStatistics summaryStats = longStream.summaryStatistics();
System.out.println(summaryStats);
LongSummaryStatistics{count=5, sum=20, min=1, average=4.000000, max=7}
首先,使用LongStream.of()方法创建一个长流。 doublestream中的summaryStatistics将收集封装在一个对象中的统计数据。 这个对象有摘要数据,比如双倍数据的计数、总和、最小、平均和最大。这是流API的还原操作,接受输入的数值数组,并给出数据摘要的输出。
LongSummaryStatistics方法
以下是java支持的长数据的汇总统计操作的内置方法
方法-说明
接受(long)-记录长数据,用于汇总操作。
Combine(LongSummaryStatistics)-将其他摘要统计合并到此,不返回。
getAverage()-返回对长值列表的平均操作,如果不存在任何值则返回0
getCount()-返回记录的长值列表的计数
getMax()-返回长值列表中的最大值。如果加入NaN值,则返回NaN,如果没有加入任何值,则返回MAX_VALUE值。
getMin()-如果添加了NaN值,则返回NaN,如果没有添加任何值,则返回MIN_VALUE值,从一个长列表中返回最小值。
getSum()-返回列表中所有长值的总和,如果没有添加任何值,则返回0。