常見(jiàn)用法
null
對(duì)象處理
@Data
@AllArgsConstructor
public class Sneakers {
private String name;
private Integer size;
private Brand brand;
}
@Data
@AllArgsConstructor
public class Brand {
private String name;
private String location;
private Person ceo;
}
@Data
@AllArgsConstructor
public class Person {
private String name;
private int age;
private String sex;
}
// 不使用Optional
Sneakers aj1 = new Sneakers("air jordan 1 black", 44, null);
if (aj1 != null && aj1.getBrand() != null && aj1.getBrand().getCeo() != null) {
System.out.println("real ceo:" + aj1.getBrand().getCeo().getName());
} else {
System.out.println("default ceo:xxxxx");
}
// console:
// default ceo:xxxxx
// 使用Optional
System.out.println("ceo:" + Optional.of(aj1).map(Sneakers::getBrand).map(Brand::getCeo).orElse(new Person("qiaodan", 44, "male")).getName());
// console:
// ceo:qiaodan
@Data
@AllArgsConstructor
public class Cat {
private String name;
private String type;
private int age;
}
List<Cat> cats = Lists.newArrayList(
new Cat("咪咪", "中華田園", 10)
, new Cat("喵喵", "波斯貓", 5)
, new Cat("阿花", "暹羅貓", 3));
System.out.println(cats.stream().findFirst().orElse(new Cat("默認(rèn)", "未知", 2)).getName());
cats.remove(0);
System.out.println(cats.stream().findFirst().orElse(new Cat("默認(rèn)", "未知", 2)).getName());
cats.clear();
System.out.println(cats.stream().findFirst().orElse(new Cat("默認(rèn)", "未知", 2)).getName());
// console:
// 咪咪
// 喵喵
// 默認(rèn)
一些坑
orElse
方法不管Optional
對(duì)象本身是不是empty
输玷,orElse
里的代碼都會(huì)被執(zhí)行
@Data
public class Cat {
private String name;
private String type;
private int age;
public Cat(String name, String type, int age) {
this.name = name;
this.type = type;
this.age = age;
System.out.println(String.format("a new cat:%s", name));
}
}
Optional
的實(shí)體是null
的時(shí)候,一切正常
Cat c1 = null;
System.out.println(Optional.ofNullable(c1).orElse(new Cat("咪咪1", "中華田園", 10)).getName());
System.out.println(Optional.ofNullable(c1).orElseGet(() -> new Cat("咪咪2", "中華田園", 10)).getName());
// console:
// a new cat:咪咪1
// 咪咪1
// a new cat:咪咪2
// 咪咪2
Optional
的實(shí)體非null
的時(shí)候蔫敲,問(wèn)題就來(lái)了
Cat c1 = new Cat("喵喵", "波斯貓", 5);
System.out.println(Optional.ofNullable(c1).orElse(new Cat("咪咪1", "中華田園", 10)).getName());
System.out.println(Optional.ofNullable(c1).orElseGet(() -> new Cat("咪咪2", "中華田園", 10)).getName());
// console:
// a new cat:喵喵
// a new cat:咪咪1
// 喵喵
// 喵喵