java8-Optional空指针处理
程序员文章站
2022-03-04 11:27:32
...
/**
* Optional.of(T t): 创建一个Optional实例
* Optional.empty(): 创建一个空的Optional实例
* Optional.ofNullable(T): 若T不为空则调用Optional.of(T t),否则调用Optional.empty()
* isPresent(): 判断是否为空值
* orElse(T t):若调用对象不为空,则返回该值,否则返回t
* orElseGet(Supplier s):如果调用对象包含值,则返回该值,否则返回S获取的值
* map(Function f):有值则进行处理并返回,否则返回Optional.empty()
* flatmap(Function f):与map类似,但返回值必须是Optional
*/
public class TestOptional {
/**
* Optional.of(T t): 创建一个Optional实例
* Optional.empty(): 创建一个空的Optional实例
* Optional.ofNullable(T): 若T不为空则调用Optional.of(T t),否则调用Optional.empty()
* isPresent(): 判断是否为空值
* orElse(T t):若调用对象不为空,则返回该值,否则返回t
* orElseGet(Supplier s):如果调用对象包含值,则返回该值,否则返回S获取的值
* map(Function f):有值则进行处理并返回,否则返回Optional.empty()
* flatmap(Function f):与map类似,但返回值必须是Optional
*/
@Test
public void test(){
Optional<Employee> optional = Optional.of(new Employee());
System.out.println("===test===");
//空参数不行
// Optional<Employee> optional = Optional.of(null);
if (optional.isPresent()) {
Employee employee = optional.get();
System.out.println(employee);
}
}
@Test
public void test2(){
System.out.println("===test2===");
try {
Optional<Employee> empty = Optional.empty();
System.out.println(empty.get());
}catch (NoSuchElementException e){
System.out.println("空指针异常");
}
}
@Test
public void test3(){
System.out.println("===test3-1===");
Optional<Employee> optional = Optional.ofNullable(null);
if (optional.isPresent()) {
Employee employee = optional.get();
System.out.println(employee);
}
System.out.println(optional.orElse(new Employee("李四",18,999,Employee.Status.FREE)));
System.out.println("===test3-2===");
System.out.println(optional.orElseGet(
() -> {
if(System.currentTimeMillis()%2==0) {
return new Employee("李四", 18, 999, Employee.Status.FREE);
}
return new Employee("王五", 18, 999, Employee.Status.FREE);
}
));
}
@Test
public void test4(){
System.out.println("===test4===");
Optional<Employee> optional = Optional.of(new Employee(null,18,999,Employee.Status.FREE));
String orElse = optional.map(Employee::getName).orElse("王五");
System.out.println(orElse);
}
@Test
public void test5(){
/**
* 如果对象存在 返回对象名字
* 如果对象存在但名字不存在,返回李四
* 如果对象不存在,返回王五
*/
System.out.println("===test5===");
Optional<Employee> optional = Optional.of(new Employee(null,18,999,Employee.Status.FREE));
String elseGet = optional.flatMap(
(employee) -> {
Optional<String> name = Optional.ofNullable(employee.getName());
if (name.isPresent()) {
return Optional.of("李四");
}
return name;
// return Optional.ofNullable(employee.getName()).orElse(Optional.empty());
}
).orElseGet(() -> "王五");
System.out.println(elseGet);
}
}
=test=
Employee{name=‘null’, age=0, salary=0.0, status=null}
=test2=
空指针异常
=test3-1=
Employee{name=‘李四’, age=18, salary=999.0, status=FREE}
=test3-2=
Employee{name=‘王五’, age=18, salary=999.0, status=FREE}
=test4=
王五
=test5=
王五
推荐阅读