测试用例类:
public class Person {
private String name;
private int age;
}
测试代码
public class Test {
public static void main(String[] args) {
Person person = null;
// 如果person为空,则new Person("123", 1)
Person person1 = Optional.ofNullable(person).orElse(new Person("123", 1));
System.out.println(person1);
// 如果person.getName()为空则返回other
String orElse3 = Optional.ofNullable(person).map((value) -> value.getName()).orElse("other");
System.out.println(orElse3);
}
}