j.dev
j.dev

Reputation: 41

Check if there are consecutive points in Java list greater than a threshold

I have a list List<Double> representing latency values collected from server metrics. I want to check if there are 3 consecutive values are greater than a given threshold.

e.g. threshold = 20

list 1: [15.121, 15.245, 20.883, 20.993, 15.378, 15.447, 15.839, 15.023] should return false because there are only two values 20.883, 20.993 that are greater than 20.

list 2: [15.121, 15.245, 20.883, 20.993, 15.378, 15.447, 20.193, 15.023] should return false because there are only three values greater than 20 but they are not consecutive.

list 3: [15.121, 15.245, 20.883, 20.993, 20.193, 15.378, 15.447, 15.023] should return true because there are three consecutive values 20.883, 20.993, 20.193 greater than 20.

I could do a loop with index to check on list.get(i-1), list.get(i), and 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();
}

Just wondering is there a more efficient way to do it?


Updated with anyMatch base on Andy Turner's comment.

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)
        );
}

Upvotes: 2

Views: 228

Answers (1)

Andy Turner
Andy Turner

Reputation: 140318

It's easiest just to do it with an enhanced for loop, keeping a count of the number of elements you have seen in a contiguous run:

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;

Upvotes: 3

Related Questions