【问题标题】:'OptionalDouble.getAsDouble()' without 'isPresent()' check'OptionalDouble.getAsDouble()' 没有 'isPresent()' 检查
【发布时间】:2021-05-10 07:55:57
【问题描述】:

我已经看到了很多解决这个问题的方法,但无论我尝试什么,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();

虽然我知道这些可选的双精度值永远不会为空,但我想解决它们,以免出现警告。

谁能指出我哪里出错了?

【问题讨论】:

    标签: java java-stream double optional


    【解决方案1】:
    double testDouble= customClass.stream()
                  .mapToDouble(CustomClass::getDouble)
                  .max().orElseThrow(IllegalStateException::new)
                  .getAsDouble();
    

    orElseThrow 返回 double,而不是 OptionalDouble。无需致电getAsDouble()

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

    【讨论】:

      【解决方案2】:

      您可以尝试以下方法:

      final double testDouble = doubles.stream()
                      .mapToDouble(CustomClass::getDouble)
                      .max()
                      .orElseThrow(IllegalArgumentException::new);
      

      OptionalDouble.getAsDouble() 如果缺少值,可能会抛出 NoSuchElementExceptionDoubleStream.max() aggregator 将在流为空时返回空 OptionalDouble(例如流空集合时),但是代码分析器很难甚至有时无法确定流是否为空,因此 IDEA 会始终警告您反对这个。

      因此,即使您“知道这些可选的双精度值永远不会为空”,IDEA 也不知道这一点。投掷IllegalArgumentException 让她平静下来。这将涵盖缺少可选最大值的可能的代码分支。

      【讨论】:

        猜你喜欢
        • 2016-12-08
        • 1970-01-01
        • 2019-12-25
        • 1970-01-01
        • 2022-01-19
        • 2019-08-09
        • 1970-01-01
        • 2023-03-03
        • 1970-01-01
        相关资源
        最近更新 更多