‘OptionalDouble.getAsDouble()’ without ‘isPresent()’ check

Tags: , , ,



I’ve seen a bunch of solutions for this question but no matter what I try, IDEA still reports an error.

Consider the following block:

double testDouble= customClass.stream()
              .mapToDouble(CustomClass::getDouble)
              .max()
              .getAsDouble();

This reports a warning of 'OptionalDouble.getAsDouble()' without 'isPresent()' check.

If I try this then it doesn’t compile:

double testDouble= customClass.stream()
              .mapToDouble(CustomClass::getDouble)
              .max().orElseThrow(IllegalStateException::new)
              .getAsDouble();

Neither does this:

double testDouble= customClass.stream()
              .mapToDouble(CustomClass::getDouble)
              .max().orElse(null)
              .getAsDouble();

Or this:

double testDouble= customClass.stream()
              .mapToDouble(CustomClass::getDouble)
              .max().isPresent()
              .getAsDouble();

While i know these optional doubles will never be null, i’d like to resolve them so there are no warnings.

Can anyone point out where i am going wrong?

Answer

double testDouble= customClass.stream()
              .mapToDouble(CustomClass::getDouble)
              .max().orElseThrow(IllegalStateException::new)
              .getAsDouble();

orElseThrow returns a double, not an OptionalDouble. There’s no need to call getAsDouble().

double testDouble = customClass.stream()
    .mapToDouble(CustomClass::getDouble)
    .max().orElseThrow(IllegalStateException::new);


Source: stackoverflow