java else if出错_Java8 Optional优雅解决if else判空问题

新建场景

学校类

/**

* 大学

*/

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;

}

}

学院类

/**

* 学院

*/

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;

}

}

系别类

/**

* 系

*/

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

完整源码

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值