Java选项:返回值或执行某些操作并继续循环
在一个循环中,我有类似的代码
for (Id id : ids) {
Item item = itemRepo.findbyId(id);
if(item == null) {
Log.error("No item by id");
continue;
}
// bla bla bla
}
使用Optionals重写此文件的最佳方法是什么
我试图重写,并希望使用ifPresentOrElse使代码更短,但方法ifPresentOrElse()是编写的
When we have an Optional instance, often we want to execute a specific action on the underlying value of it. On the other hand, if the Optional is empty we want to log it or track that fact by incrementing some metric.
因此,如果有值,我就不能返回它。 有什么建议吗
多谢各位
更新:很抱歉,我忘了提到我需要可选的解决方案,因为存储库函数getById已经更改,它返回可选的结果强>
# 1 楼答案
使用Optional的一个很好的用例是通过避免不必要的空检查来编写整洁的代码。 因此,在代码中有一个地方可以使用可选选项-
上述代码的限制是,如果项为null,则不会收到通知。如果需要,可以使用以下代码
# 2 楼答案
# 3 楼答案
我认为这里不需要
Optional
,一个简单的else
就行了# 4 楼答案
我也不太喜欢选修课。但如果您想使用它,这可能会起作用:
在我看来,Optionals应该与streams一起使用。for循环是流的最佳候选