本文共 4840 字,大约阅读时间需要 16 分钟。
内容来自《 java8实战 》,本篇文章内容均为非盈利,旨为方便自己查询、总结备份、开源分享。如有侵权请告知,马上删除。
书籍购买地址:
如下代码
public class Person { private Car car; public Car getCar() { return car; }}public class Car { private Insurance insurance; public Insurance getInsurance() { return insurance; }}public class Insurance{ private String name; public String getName() { return name; }}//将要使用的代码public String getCarInsuranceName(Person person){ return person.getCar().getInsurance().getName();}
如上代码如果使用,如果某个Person没有车,那么就会引发空指针异常,在平常我们使用if来去判断的,比如
public String getCarInsuranceName(Person person){ if (null != person){ Car car = person.getCar(); if (null != car){ Insurance insurance = car.getInsurance(); if (insurance != null) { return insurance.getName(); } } } return "UnKnow";}
或者更容易读的是这样的,避免了if的嵌套难以阅读
public String getCarInsuranceName(Person person){ if (person == null) { return "UnKnow"; } Car car = person.getCar(); if (car == null){ return "UnKnow"; } Insurance insurance = car.getInsurance(); if (insurance == null) { return "UnKnow"; } return insurance.getName();}
使用Optional重新定义bean对象
public class Person { private Optionalcar; public Optional getCar() { return car; }}public class Car { private Optional insurance; public Optional getInsurance() { return insurance; }}public class Insurance{ private String name; //公司肯定有名字 public String getName() { return name; }}
Optional.empty()
Optional.of(notnullobj)
,如果notnullobj是一个空对象,那么就会抛出空指针异常Optional.ofNullable(car)
,car对象可以是空对象也可以不是空对象,如果是空对象则得到一个空的OptionalString name = null;if (insurance != null){ name = insurance.getName();}
如上是原来的提取的代码,先判断在取值,避免空指针,如下使用Optional
Optionalname = Optional.ofNullable(insurance).map(Insurance::getName);
本文开头提到的这样一连串的调用,怎么用Optional解决呢?
//原来public String getCarInsuranceName(Person person){ return person.getCar().getInsurance().getName();}
public String getCarInsuranceName(Optionalperson){ person.map(Person::getCar) .map(Car::getInsurance) .map(Insurance::getName);}
public String getCarInsuranceName(Optionalperson){ return person.flatMap(Person::getCar) .flatMap(Car::getInsurance) .map(Insurance::getName) .orElse("Unknow");}
为什么?
public class Car { private Insurance insurance; public OptionalgetInsuranceAsOptional() { return Optional.ofNullable(insurance); }}
如果需要判断某个公司,那么我们需要这样的判断
Insurance insurance = ...;if (null != insurance && "lalala".equals(insurance.getName())){ System.out.println("...");}
使用filter方法
Optionalinsurance = null;insurance.filter(i -> "lalala".equals(i.getName())) .ifPresent(i -> System.out.println("..."));
需求:输入参数转换为int,然后返回该转换后的值,出错的话就返回0
public Integer StringParse(String str){ if (null == str) return 0; try { return Integer.parseInt(str); }catch (NumberFormatException e){ return 0; }}
用Optional解决
public OptionalStringParse(String str){ try { return Optional.of(Integer.parseInt(str)); }catch (NumberFormatException e){ return Optional.empty(); }}
转载地址:http://qeelo.baihongyu.com/