不存在类型变量 U 的实例,因此 void 符合 U

nik*_*kel 2 java functional-programming java-stream option-type

我试图避免isPresent检查下面的代码,但编译器会发出错误消息

“不存在类型变量的实例,U因此void符合U

致电printAndThrowException. 这是我的代码:

values.stream()
    .filter(value -> getDetails(value).getName.equals("TestVal"))
    .findFirst()
    .map(value -> printAndThrowException(value))
    .orElseThrow(new Exception2("xyz"));
Run Code Online (Sandbox Code Playgroud)

所讨论的 printAndThrowException 方法具有以下签名:

void printAndThrowException(Pojo value)
Run Code Online (Sandbox Code Playgroud)

上面的方法总是抛出类型为 的异常RuntimeException。上述代码不是确切的代码,只是对我的代码进行了转换以代表情况。

这里有什么问题以及如何避免isPresent在调用时使用printAndThrowException

Did*_*r L 9

Optional.map()需要一个Function<? super T, ? extends U>作为参数。由于您的方法返回void,因此不能在 lambda 中像这样使用它。

\n

我在这里看到三个选项:

\n
    \n
  • 使该方法返回Void// Objectwhatever 而 \xe2\x80\x93 在语义上并不理想,但它会起作用
  • \n
  • 使该方法返回异常,并将 lambda 定义更改为\n
    .map(v -> {\n    throw printAndReturnException();\n});\n
    Run Code Online (Sandbox Code Playgroud)\n
  • \n
  • 使用ifPresent(),并将其移至orElseThrow()调用链之外:\n
    values.stream()\n    .filter(value -> getDetails(value).getName.equals("TestVal"))\n    .findFirst()\n    .ifPresent(value -> printAndThrowException(value))\nthrow new Exception2("xyz");\n
    Run Code Online (Sandbox Code Playgroud)\n
  • \n
\n