@Test
void contextLoads() {
// 当对象为null时
User user = null;
Optional.ofNullable(user).orElse(createUser("orElse"));
Optional.ofNullable(user).orElseGet(() -> createUser("orElseGet"));
/** 输出
* create User:orElse
* create User:orElseGet
*/
// 当对象不为null时
User user = new User("zhang", 18);
Optional.ofNullable(user).orElse(createUser("orElse"));
Optional.ofNullable(user).orElseGet(() -> createUser("orElseGet"));
/** 输出
* create User:orElse
*/
}
private User createUser(String msg) {
System.out.println("create User:" + msg);
return new User("小张", 20);
}
// 测试对象类
class User {
private String name;
private int age;
public User(String name, int age) {
this.name = name;
this.age = age;
}
}
总结
- 使用orElse时,ofNullable参数对象不论是否为null都会执行orElse的方法;
- 使用orElseGet时,只有ofNullable参数对象为null时才会执行orElseGet里的方法;