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?
Optional.map()需要一个Function<? super T, ? extends U>作为参数。由于您的方法返回void,因此不能在 lambda 中像这样使用它。
我在这里看到三个选项:
\nVoid// Objectwhatever 而 \xe2\x80\x93 在语义上并不理想,但它会起作用.map(v -> {\n throw printAndReturnException();\n});\nRun Code Online (Sandbox Code Playgroud)\nifPresent(),并将其移至orElseThrow()调用链之外:\nvalues.stream()\n .filter(value -> getDetails(value).getName.equals("TestVal"))\n .findFirst()\n .ifPresent(value -> printAndThrowException(value))\nthrow new Exception2("xyz");\nRun Code Online (Sandbox Code Playgroud)\n| 归档时间: |
|
| 查看次数: |
34688 次 |
| 最近记录: |