java - 检查Java列表中是否存在大于阈值的连续点

标签 java list

我有一个 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/

相关文章:

c# - 如何提取列表中具有相同值的项目数?

Java Scanner(File) 行为异常,但 Scanner(FIleInputStream) 始终处理同一个文件

java - 如何删除 <ref> 和 </ref> 之间的文本

Python:列表索引必须是整数,而不是元组

c# - 在 List<T> 中搜索匹配的 2 列

jquery:在图像后淡入淡出

java - 选择排序法

java - Eclipse:设置操作的悬停图像

Java - 添加行有更有效的方法吗?

python - 在随机列表生成中强制执行 "no 2 same contiguous elements"