我有一个 list List<Double>
表示从服务器指标收集的延迟值。我想检查是否有 3 个连续值大于给定阈值。
例如阈值 = 20
列表 1:[15.121, 15.245, 20.883, 20.993, 15.378, 15.447, 15.839, 15.023]
应该返回 false,因为只有两个值 20.883, 20.993
大于 20。
列表 2:[15.121, 15.245, 20.883, 20.993, 15.378, 15.447, 20.193, 15.023]
应该返回 false,因为只有三个值大于 20,但它们不连续。
列表 3:[15.121, 15.245, 20.883, 20.993, 20.193, 15.378, 15.447, 15.023]
应该返回 true,因为有三个连续值 20.883, 20.993, 20.193
大于 20。
我可以使用索引进行循环来检查 list.get(i-1)、list.get(i) 和 list.get(i+1)。
public boolean isAboveThreshold(List<Double> list, Double threshold) {
// CONSECUTIVE_NUMBER = 3
if (list.size() < CONSECUTIVE_NUMBER) {
return false;
}
return !IntStream.range(0, list.size() - 2)
.filter(i -> list.get(i) > threshold && list.get(i + 1) > threshold && list.get(i + 2) > thread)
.collect(Collectors.toList())
.isEmpty();
}
只是想知道是否有更有效的方法?
更新为anyMatch
基于Andy Turner的评论。
public boolean isAboveThreshold(List<Double> values, Double threshold, int consecutiveNumber) {
if (values.size() < consecutiveNumber) {
return false;
}
return IntStream
.range(0, values.size() - consecutiveNumber + 1)
.anyMatch(index ->
IntStream.range(index, index + consecutiveNumber)
.allMatch(i -> values.get(i) > threshold)
);
}
最佳答案
最简单的方法是使用增强的 for 循环,记录在连续运行中看到的元素数量:
int count = 0;
for (double d : list) {
if (d >= threshold) {
// Increment the counter, value was big enough.
++count;
if (count >= 3) {
return true;
}
} else {
// Reset the counter, value too small.
count = 0;
}
}
return false;
关于java - 检查Java列表中是否存在大于阈值的连续点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60459465/