我试图理解Java 8中API 的ifPresent()方法Optional.
我有简单的逻辑:
Optional<User> user=...
user.ifPresent(doSomethingWithUser(user.get()));
Run Code Online (Sandbox Code Playgroud)
但这会导致编译错误:
ifPresent(java.util.functionError:(186, 74) java: 'void' type not allowed here)
Run Code Online (Sandbox Code Playgroud)
我当然可以这样做:
if(user.isPresent())
{
doSomethingWithUser(user.get());
}
Run Code Online (Sandbox Code Playgroud)
但这就像一张杂乱无章的null支票.
如果我将代码更改为:
user.ifPresent(new Consumer<User>() {
@Override public void accept(User user) {
doSomethingWithUser(user.get());
}
});
Run Code Online (Sandbox Code Playgroud)
代码变得越来越脏,这让我想到回到旧的null支票.
有任何想法吗?
Optional在Java中,我最近开始在我的代码中更多地采用这种类型。这允许更好的null值处理并且在某种程度上也更安全的代码。Optional具有ifPresentOrElse允许您在存在值时执行特定操作或在不存在值时执行特定操作的方法。但是,此方法不允许您声明返回类型。
有没有一种简单的方法可以ifPresentOrElse在展开时使用可选值和类似方法来返回值Optional?
我想做的是,如果存在客户,则更新客户,但如果没有客户,则抛出异常。但我找不到正确的流函数来做到这一点。我怎样才能做到这一点?
public Customer update(Customer customer) throws Exception {
Optional<Customer> customerToUpdate = customerRepository.findById(customer.getId());
customerToUpdate.ifPresentOrElse(value -> return customerRepository.save(customer),
throw new Exception("customer not found"));
}
Run Code Online (Sandbox Code Playgroud)
我无法返回来自保存函数的值,因为它说它是 void 方法并且不期望返回值。
我是一个相对新手的 Stream 用户,我觉得应该有一种更简洁的方法来完成我下面的操作。是否可以在单个 Stream 中完成以下代码的全部操作(消除底部的 if/else)?
谢谢!
Optional<SomeMapping> mapping = allMappings.stream()
.filter(m -> category.toUpperCase().trim().equalsIgnoreCase(m.getCategory().toUpperCase().trim()))
.findAny();
if (mapping.isPresent()) {
return mapping.get();
} else {
throw new SomeException("No mapping found for category \"" + category + "\.");
}
Run Code Online (Sandbox Code Playgroud) java ×4
option-type ×2
optional ×2
exception ×1
java-8 ×1
lambda ×1
null ×1
nullable ×1
spring ×1
spring-boot ×1