'OptionalDouble.getAsDouble()' 没有 'isPresent()' 检查
'OptionalDouble.getAsDouble()' without 'isPresent()' check
这个问题我看了一堆解法,但是不管我怎么试,IDEA还是报错。
考虑以下块:
double testDouble= customClass.stream()
.mapToDouble(CustomClass::getDouble)
.max()
.getAsDouble();
这会报告 'OptionalDouble.getAsDouble()' without 'isPresent()' check
的警告。
如果我尝试这样做,它不会编译:
double testDouble= customClass.stream()
.mapToDouble(CustomClass::getDouble)
.max().orElseThrow(IllegalStateException::new)
.getAsDouble();
这也不行:
double testDouble= customClass.stream()
.mapToDouble(CustomClass::getDouble)
.max().orElse(null)
.getAsDouble();
或者这样:
double testDouble= customClass.stream()
.mapToDouble(CustomClass::getDouble)
.max().isPresent()
.getAsDouble();
虽然我知道这些可选的双打永远不会为空,但我想解决它们以便没有警告。
谁能指出我哪里错了?
您可以尝试以下方法:
final double testDouble = doubles.stream()
.mapToDouble(CustomClass::getDouble)
.max()
.orElseThrow(IllegalArgumentException::new);
如果缺少值,OptionalDouble.getAsDouble()
可能会抛出 NoSuchElementException
。 DoubleStream.max()
聚合器将 return 清空 OptionalDouble
当流为空时(例如,流式传输空集合时),但代码分析器很难甚至有时无法确定流是否为空空的,所以 IDEA 会一直警告你不要这样做。
所以即使你“知道这些可选的双打永远不会为空”,IDEA 也不知道这一点。扔 IllegalArgumentException
让她平静下来。这将涵盖可能缺少可选最大值的代码分支。
double testDouble= customClass.stream()
.mapToDouble(CustomClass::getDouble)
.max().orElseThrow(IllegalStateException::new)
<del>.getAsDouble()</del>;
orElseThrow
returns一个double
,不是一个OptionalDouble
。无需调用 getAsDouble()
.
double testDouble = customClass.stream()
.mapToDouble(CustomClass::getDouble)
.max().orElseThrow(IllegalStateException::new);
这个问题我看了一堆解法,但是不管我怎么试,IDEA还是报错。
考虑以下块:
double testDouble= customClass.stream()
.mapToDouble(CustomClass::getDouble)
.max()
.getAsDouble();
这会报告 'OptionalDouble.getAsDouble()' without 'isPresent()' check
的警告。
如果我尝试这样做,它不会编译:
double testDouble= customClass.stream()
.mapToDouble(CustomClass::getDouble)
.max().orElseThrow(IllegalStateException::new)
.getAsDouble();
这也不行:
double testDouble= customClass.stream()
.mapToDouble(CustomClass::getDouble)
.max().orElse(null)
.getAsDouble();
或者这样:
double testDouble= customClass.stream()
.mapToDouble(CustomClass::getDouble)
.max().isPresent()
.getAsDouble();
虽然我知道这些可选的双打永远不会为空,但我想解决它们以便没有警告。
谁能指出我哪里错了?
您可以尝试以下方法:
final double testDouble = doubles.stream()
.mapToDouble(CustomClass::getDouble)
.max()
.orElseThrow(IllegalArgumentException::new);
如果缺少值,OptionalDouble.getAsDouble()
可能会抛出 NoSuchElementException
。 DoubleStream.max()
聚合器将 return 清空 OptionalDouble
当流为空时(例如,流式传输空集合时),但代码分析器很难甚至有时无法确定流是否为空空的,所以 IDEA 会一直警告你不要这样做。
所以即使你“知道这些可选的双打永远不会为空”,IDEA 也不知道这一点。扔 IllegalArgumentException
让她平静下来。这将涵盖可能缺少可选最大值的代码分支。
double testDouble= customClass.stream() .mapToDouble(CustomClass::getDouble) .max().orElseThrow(IllegalStateException::new) <del>.getAsDouble()</del>;
orElseThrow
returns一个double
,不是一个OptionalDouble
。无需调用 getAsDouble()
.
double testDouble = customClass.stream()
.mapToDouble(CustomClass::getDouble)
.max().orElseThrow(IllegalStateException::new);