使用Stream从HashSet中排除极值 [英] Excluding extrema from HashSet with a Stream
本文介绍了使用Stream从HashSet中排除极值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我一直在尝试使用Java 8流,这是删除最低和最高分数的最佳方法。
I've been experimenting with Java 8 streams, is this is best way to remove the min and max scores.
private final Set<MatchScore> scores = new HashSet<>(10);
. . .
public double OPR() {
return scores.stream()
.mapToDouble(MatchScore::getScore)
.filter((num) -> { //Exclude min and max score
return num != scores.stream()
.mapToDouble(MatchScore::getScore)
.max().getAsDouble()
&&
num != scores.stream()
.mapToDouble(MatchScore::getScore)
.min().getAsDouble();
})
.average().getAsDouble();
}
推荐答案
更简单的方法是:
return scores.stream()
.mapToDouble(MatchScore::getScore)
.sorted()
.skip(1)
.limit(scores.size() - 2)
.average().getAsDouble();
注意:这是有效的,因为集合中的元素是唯一的 - 列表中可能有多个元素元素等于最小或最大分数。
Note: that works because elements in a set are unique - with a list there could be more than one element equal to the min or max score.
性能明智*,跳过/限制在一小部分上明显加快10个元素(均值列显示样本调用的平均时间,以纳秒为单位):
Performance wise*, the skip/limit is significantly faster on a small set of 10 elements (the Mean column shows the average time taken by a sample call, in nanoseconds):
Benchmark Mode Samples Mean Mean error Units
c.a.p.SO22923505.maxMin avgt 5 6996.190 284.287 ns/op
c.a.p.SO22923505.skipLimit avgt 5 479.935 4.547 ns/op
*使用jmh - 这里是测试的源代码。
这篇关于使用Stream从HashSet中排除极值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文