jdk8新增 optional 用法
程序员文章站
2022-06-07 20:26:01
...
1 创建optional
Optional<Department> department = Optional.empty(); 创建空对象
Optional<Employee> optEmployee = Optional.of(employee); 创建非空对象
Optional<Employee> optEmployee = Optional.ofNullable(employee); 允许为空的对象
2 optional方法
isPresent 如果值存在返回true,否则返回false
get 有值则将其返回,无值抛异常
ifPresent 值则为其调用(函数描述符为T -> void),否则不做处理
orElse 有值则将其返回,否则返回orElse方法传入的参数(前后类型要一致int string)
orElseGet 类似上述,相当于生成默认值
orElseThrow 有值则将其返回,否则抛出自定义异常
map 有值执行函数(返回optional封装对象),无值返回optional空对象
flatMap 有值执行函数,返回对象,无值返回optional空对象
用法
Optional<Department> opt = Optional.ofNullable(department);
if(opt.isPresent()){
System.out.println(opt.get().getEmployee());
}
girl.ifPresent(g -> System.out.println("我有女朋友,名字是:" + g.getName()));
System.out.println(Optional.empty().orElse("There is no value present!"));
System.out.println(Optional.empty().orElseGet(() -> "There is no value present!"));
try {
Optional.empty().orElseThrow(NoSuchElementException::new);
} catch (Exception e) {
e.printStackTrace();
}
Optional<String> upperName = name.map(String::toUpperCase);
System.out.println(upperName.orElse("No value found"));
upperName = name.flatMap((value) -> Optional.of(value.toUpperCase()));
System.out.println(upperName.orElse("No value found"));
Optional改善一开始的代码:
static String getGirlFriendName(Department department) {
Optional<Department> opt = Optional.ofNullable(department);
return opt.map(Department::getEmployee)
.map(Employee::getGirlFriend)
.map(Girl::getName)
.orElseThrow(NoSuchElementException::new);
}