- Optional 是为核心类库新设计的一个数据类型,用来替换 null 值。
- 人们对原有的 null 值有很多抱怨,甚至连发明这一概念的Tony Hoare也是如此,他曾说这是自己的一个“价值连城的错误”
- 用处很广,不光在lambda中,哪都能用
- Optional.of(T),T为非空,否则初始化报错
- Optional.ofNullable(T),T为任意,可以为空
- isPresent(),相当于 !=null
- ifPresent(T), T可以是一段lambda表达式 ,或者其他代码,非空则执行
public static void main(String[] args) {
PersonModel personModel=new PersonModel();
//对象为空则打出 -
Optional<Object> o = Optional.of(personModel);
System.out.println(o.isPresent()?o.get():"-");
//名称为空则打出 -
Optional<String> name = Optional.ofNullable(personModel.getName());
System.out.println(name.isPresent()?name.get():"-");
//如果不为空,则打出xxx
Optional.ofNullable("test").ifPresent(na->{
System.out.println(na+"ifPresent");
});
//如果空,则返回指定字符串
System.out.println(Optional.ofNullable(null).orElse("-"));
System.out.println(Optional.ofNullable("1").orElse("-"));
//如果空,则返回 指定方法,或者代码
System.out.println(Optional.ofNullable(null).orElseGet(()->{
return "hahah";
}));
System.out.println(Optional.ofNullable("1").orElseGet(()->{
return "hahah";
}));
//如果空,则可以抛出异常
System.out.println(Optional.ofNullable("1").orElseThrow(()->{
throw new RuntimeException("ss");
}));
// Objects.requireNonNull(null,"is null");
//利用 Optional 进行多级判断
EarthModel earthModel1 = new EarthModel();
//old
if (earthModel1!=null){
if (earthModel1.getTea()!=null){
//...
}
}
//new
Optional.ofNullable(earthModel1)
.map(EarthModel::getTea)
.map(TeaModel::getType)
.isPresent();
// Optional<EarthModel> earthModel = Optional.ofNullable(new EarthModel());
// Optional<List<PersonModel>> personModels = earthModel.map(EarthModel::getPersonModels);
// Optional<Stream<String>> stringStream = personModels.map(per -> per.stream().map(PersonModel::getName));
//判断对象中的list
Optional.ofNullable(new EarthModel())
.map(EarthModel::getPersonModels)
.map(pers->pers
.stream()
.map(PersonModel::getName)
.collect(toList()))
.ifPresent(per-> System.out.println(per));
List<PersonModel> models=Data.getData();
Optional.ofNullable(models)
.map(per -> per
.stream()
.map(PersonModel::getName)
.collect(toList()))
.ifPresent(per-> System.out.println(per));
}
- 影响性能的五要素是:数据大小、源数据结构、值是否装箱、可用的CPU核数量,以及处理每个元素所花的时间
- https://www.toutiao.com/a6676023517021995532/