在掘金上看到了一篇关于java8新特性OPTIONAL的使用,
想来平时编写代码过程中判null的情况还是很多,特意记录下。
User 结构
public class User {
private String name;
public String getName() {
return name;
}
}
使用optional 获取 name
String name = Optional.ofNullable(user).map(u-> u.getName()).get();
例子:
代码:
public String getCity(User user) throws Exception{
if(user!=null){
if(user.getAddress()!=null){
Address address = user.getAddress();
if(address.getCity()!=null){
return address.getCity();
}
}
}
throw new Excpetion("取值错误");
}
使用OPTIONAL :
public String getCity(User user) throws Exception{
return Optional.ofNullable(user)
.map(u-> u.getAddress())
.map(a->a.getCity())
.orElseThrow(()->new Exception("取指错误"));
}
代码:
if(user!=null){
dosomething(user);
}
使用OPTIONAL :
Optional.ofNullable(user)
.ifPresent(u->{
dosomething(u);
});
代码:
public User getUser(User user) throws Exception{
if(user!=null){
String name = user.getName();
if("zhangsan".equals(name)){
return user;
}
}else{
user = new User();
user.setName("zhangsan");
return user;
}
}
使用OPTIONAL :
public User getUser(User user) {
return Optional.ofNullable(user)
.filter(u->"zhangsan".equals(u.getName()))
.orElseGet(()-> {
User user1 = new User();
user1.setName("zhangsan");
return user1;
});
}