我试图理解Java8中的ifPresent() API的Optional方法。
我有一个简单的逻辑:
Optional<User> user=...
user.ifPresent(doSomethingWithUser(user.get()));但这会导致编译错误:
ifPresent(java.util.functionError:(186, 74) java: 'void' type not allowed here)我当然可以做这样的事:
if(user.isPresent())
{
doSomethingWithUser(user.get());
}但这就像一张杂乱的null支票。
如果我将代码更改为:
user.ifPresent(new Consumer<User>() {
@Override public void accept(User user) {
doSomethingWithUser(user.get());
}
});代码变得越来越脏,这让我想到回到旧的null检查。
有什么想法吗?
发布于 2017-04-26 07:34:40
除了@JBNizet的答案之外,我对ifPresent的一般用例是将.isPresent()和.get()结合起来
旧方式:
Optional opt = getIntOptional();
if(opt.isPresent()) {
Integer value = opt.get();
// do something with value
}新途径:
Optional opt = getIntOptional();
opt.ifPresent(value -> {
// do something with value
})对我来说,这更直观。
https://stackoverflow.com/questions/24228279
复制相似问题