Preface
Java8 new features: Optional
It is a container object that can be null. Optional provides many useful methods, so that we don't need to explicitly check for null values, and can make our code more elegant and impressive.
Before Java8, the commonly used method of emptying
Student object
@Data
public class Student {
private String name;
private Hobby hobby;
public Optional<Hobby> getHobbyOfNull(){
return Optional.ofNullable(this.hobby);
}
}
Hobby object
@Data
public class Hobby {
private String name;
}
String name = student.getName();
String hobbyName = student.getHobby().getName();
When the object is null, direct reference will cause a NullPointerException. You need to make a null judgment before calling each object.
// 示例一 嵌套参数
String name ="";
if(student != null){
if (student.getName() != null){
name = student.getName();
}
}
//示例二 嵌套对象
String hobbyName ="";
if(student != null){
Hobby hobby = student.getHobby();
if (hobby != null && hobby.getName() != null){
hobbyName = hobby.getName();
}
}
When there are more hierarchical relationships, the code will be very bloated
Optional way
示例一
String name = Optional.ofNullable(student).map(e -> e.getName()).orElse("");
示例二
hobbyName = Optional.ofNullable(student).flatMap(Student::getHobbyOfNull).map(Hobby::getName).orElse("");