xai-org/x-algorithm · error · NoSuchElementException

collection is empty

Error message

collection is empty

What it means

Max.apply throws NoSuchElementException("collection is empty") when the input collection of numbers contains no elements, because the loop never assigns a non-null max. It mirrors Guava's/Scala's empty-collection semantics for aggregate functions.

Source

Thrown at botmaker/src/java/com/twitter/botmaker/function/math/Max.java:58

  public Signature getSignature() {
    return SIGNATURE;
  }

  @Override
  protected CacheLevel getCacheLevel() {
    return CacheLevel.Global;
  }

  @Override
  protected Object apply(Context<Runtime> context, List<Number> numbers) {
    Number max = null;
    for (Number num : numbers) {
      if (max == null || max.doubleValue() < num.doubleValue()) {
        max = num;
      }
    }
    if (max == null) {
      throw new NoSuchElementException("collection is empty");
    }
    return max;
  }
}

View on GitHub (pinned to 24c60942c5)

Solutions

  1. Filter out or default empty collections before applying Max (e.g. coalesce to 0 or skip the aggregation)
  2. Wrap the expression with an emptiness check: If(IsEmpty(list), default, Max(list))
  3. If empty input is legitimately an error, catch NoSuchElementException at the pipeline boundary

Example fix

// before
Number m = Max().apply(ctx, numbers); // numbers empty -> NoSuchElementException
// after
Number m = numbers.isEmpty() ? 0 : (Number) Max().apply(ctx, numbers);
Defensive patterns

Strategy: validation

Validate before calling

if (numbers == null || numbers.isEmpty()) {
  return DEFAULT_VALUE; // or skip aggregation
}
return Max().apply(ctx, numbers);

Type guard

public static boolean nonEmpty(Collection<?> c) { return c != null && !c.isEmpty(); }

Try / catch

try {
  return (Number) Max().apply(ctx, numbers);
} catch (NoSuchElementException e) {
  return emptyDefault; // e.g. 0.0 or Optional.empty upstream
}

Prevention

When it happens

Trigger: Calling Max() on an empty list, e.g. Max().apply(ctx, ImmutableList.of()) or an expression aggregating over an empty partition/window.

Common situations: Aggregating over empty group-bys, empty filtered datasets, time windows with no events, or optional lists that defaulted to empty.

Related errors


AI-assisted analysis of xai-org/x-algorithm@24c60942c5 (2026-08-28). Data as JSON: /api/errors/350c2cec3adeafe2. Report an issue: GitHub.