1-判断对象为空
平常我们写空判断对象代码如下:
Student student = new Student("haha");
student = null;
if (student != null) {
String name = student.getName();
}
替换为 Optional 类型直进行判空,缺点直接判断 代码依旧冗余。代码如下:
Optional<Student> studentB = Optional.ofNullable(student);
if (studentB.isPresent()) {
System.out.println(studentB.get().getName());
}
正确的做法 建议使用流式操作,代码如下:
Optional.ofNullable(student).ifPresent(stu -> System.out.println(stu.getName()));
2-再比如获取获取对象中的类,为空就抛出异常
正常判断为空的写法
if (student != null) {
if (student.getAddress() != null) {
Address address = student.getAddress();
if (address.getCity() != null) {
System.out.println(address.getCity());
}
}
}
throw new RuntimeException("有空值");
正确的流式操作
Optional.ofNullable(student)
.map(Student::getAddress)
.map(Address::getCity)
.orElseThrow(() -> new Exception("有空值"));
3-再比如获取名字为小马哥的学生,如果为空就返回一个新对象
平常的写法
public Student getStudent(Student student) throws RuntimeException {
if (student != null) {
String name = student.getName();
if ("xiaomage".equals(name)) {
return student;
}
student = new Student();
student.setName("xiaomage");
return student;
} else {
student = new Student();
student.setName("xiaomage");
return student;
}
}
Optional 流方式操作写法
public Student getStudent2(Student student) {
return Optional.ofNullable(student)
.filter(stu -> "xiaomage".equals(stu.getName()))
.orElseGet(() -> {
Student studentNew = new Student();
studentNew.setName("xiaomage");
return studentNew;
});
}