Java8 Optional优雅解决if else判空问题

2020-05-24  本文已影响0人  shiguangfeixu

新建场景

  1. 学校类
/**
 * 大学
 */
class University {
    private College college;

    public University(College college) {
        this.college = college;
    }

    public College getCollege() {
        return college;
    }

    public void setCollege(College college) {
        this.college = college;
    }
}
  1. 学院类
/**
 * 学院
 */
class College {
    private Department department;

    public College(Department department) {
        this.department = department;
    }

    public Department getDepartment() {
        return department;
    }

    public void setDepartment(Department department) {
        this.department = department;
    }
}
  1. 系别类
/**
 * 系
 */
class Department {
    private String name;

    public Department(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

其中学校包含学院,学院包含系别

private static final University UNIVERSITY_1 =  new University(new College(new Department("Tongji CS")));
private static final University UNIVERSITY_2 =  new University(new College(null));
private static final University UNIVERSITY_3 =  new University(null);
private static final University UNIVERSITY_4 =  null;

问题提出

如果想从一个University对象中直接取出系别Department的名称,可能要一步一步进行get判空,类似于这样,否则直接一步get可能会出现NPE问题。

    public static String getUniversityWithIfElse(University university){
        if(university == null){
            return null;
        }
        if(university.getCollege() == null){
            return null;
        }
        if(university.getCollege().getDepartment()==null){
            return null;
        }
        if(university.getCollege().getDepartment().getName()==null){
            return null;
        }
        return university.getCollege().getDepartment().getName();
    }

使用Java8之后,我们的代码不在像以前那么臃肿,可以更加优雅的获取其中的数据,类似于这样

    public static String getUniversityWithOptional(University university){
        return Optional.ofNullable(university).map(University::getCollege).map(College::getDepartment).map(Department::getName).orElse(null);
    }

上述两种方式允许结果

Java8 Optional
Tongji CS
null
null
null
Java If Else
Tongji CS
null
null
null

完整源码

Java8 Trick

上一篇下一篇

猜你喜欢

热点阅读