一、Optional.ofNullable
1.1 Demo 1
Account account = Optional.ofNullable(databaseUserRepo.findByUsername(username)).orElseThrow(() -> new UsernameNotFoundException("用户" + username + "不存在"))
1.2 Demo 2
Optional.ofNullable(uiConfiguration).orElse(UiConfigurationBuilder.builder().build())
二、orElseGet
Optional<Wallet> findByAccountId(Integer accountId);
//为null时,创建一下新的
Wallet wallet = repository.findByAccountId(accountId).orElseGet(() -> {
Wallet newWallet = new Wallet();
Account account = new Account();
account.setId(accountId);
newWallet.setMoney(0D);
newWallet.setAccount(account);
repository.save(newWallet);
return newWallet;
});
补充:orElse方法传入的参数是明确的默认值,orElseGet方法传入的参数是获取默认值的函数。
三、map/flatMap获取关联数据
import java.util.Optional;
public class Client {
public static void main(String[] args) {
//测试1
Person person = new Person();
System.out.println(getCarInsuranceName(person));
System.out.println(getCarInsuranceName2(person));
System.out.println("--------------------------");
//测试2
Insurance insurance = new Insurance("xx保险公司");
Car car = new Car(insurance);
Person person2 = new Person(car);
System.out.println(getCarInsuranceName(person2));
System.out.println(getCarInsuranceName2(person2));
}
/**
* 常规实现:根据客户信息获取车辆保险公司的名称
*
* @param person
* @return
*/
public static String getCarInsuranceName(Person person) {
//对客户判空
if (person == null) {
return "Unknown";
}
//对车辆判空
Car car = person.getCar();
if (car == null) {
return "Unknown";
}
//对保险公司判空
Insurance insurance = car.getInsurance();
if (insurance == null) {
return "Unknown";
}
return insurance.getName();
}
/**
* Optional实现:根据客户信息获取车辆保险公司的名称
*
* @param person
* @return
*/
public static String getCarInsuranceName2(Person person) {
//当Optional对象为空时,则后面的map都不会继续执行
return Optional.ofNullable(person)
.map(Person::getCar)
.map(Car::getInsurance)
.map(Insurance::getName)
.orElse("Unknown");
}
}
网友评论