在文章的开头,先说下NPE问题,NPE问题就是,我们在开发中经常碰到的NullPointerException.假设我们有两个类,他们的UML类图如下图所示
user.getAddress().getProvince();
if(user!=null){
Address address = user.getAddress();
if(address!=null){
String province = address.getProvince();
}
}
Optional(T value),empty(),of(T value),ofNullable(T value)
public static <T> Optional<T> of(T value) {
return new Optional<>(value);
}
-
通过of(T value)函数所构造出的Optional对象,当Value值为空时,依然会报NullPointerException。
-
通过of(T value)函数所构造出的Optional对象,当Value值不为空时,能正常构造Optional对象。
public final class Optional<T> {
//省略....
private static final Optional<?> EMPTY = new Optional<>();
private Optional() {
this.value = null;
}
//省略...
public static<T> Optional<T> empty() {
@SuppressWarnings("unchecked")
Optional<T> t = (Optional<T>) EMPTY;
return t;
}
}
public static <T> Optional<T> ofNullable(T value) {
return value == null ? empty() : of(value);
}
orElse(T other),orElseGet(Supplier<? extends T> other)和orElseThrow(Supplier<? extends X> exceptionSupplier)
@Test
public void test() {
User user = null;
user = Optional.ofNullable(user).orElse(createUser());
user = Optional.ofNullable(user).orElseGet(() -> createUser());
}
public User createUser(){
User user = new User();
user.setName("zhangsan");
return user;
}
User user = null;
Optional.ofNullable(user).orElseThrow(()->new Exception("用户不存在"));
map(Function<? super T, ? extends U> mapper)和flatMap(Function<? super T, Optional<U>> mapper)
public final class Optional<T> {
//省略....
public<U> Optional<U> map(Function<? super T, ? extends U> mapper) {
Objects.requireNonNull(mapper);
if (!isPresent())
return empty();
else {
return Optional.ofNullable(mapper.apply(value));
}
}
//省略...
public<U> Optional<U> flatMap(Function<? super T, Optional<U>> mapper) {
Objects.requireNonNull(mapper);
if (!isPresent())
return empty();
else {
return Objects.requireNonNull(mapper.apply(value));
}
}
}
Function<? super T, ? extends U>
,而flapMap的入参类型为
Function<? super T, Optional<U>>
。
public class User {
private String name;
public String getName() {
return name;
}
}
String city = Optional.ofNullable(user).map(u-> u.getName()).get();
public class User {
private String name;
public Optional<String> getName() {
return Optional.ofNullable(name);
}
}
String city = Optional.ofNullable(user).flatMap(u-> u.getName()).get();
isPresent()
和
ifPresent(Consumer<? super T> consumer)
public final class Optional<T> {
//省略....
public boolean isPresent() {
return value != null;
}
//省略...
public void ifPresent(Consumer<? super T> consumer) {
if (value != null)
consumer.accept(value);
}
}
if (user != null){ // TODO: do something}
给写成
User user = Optional.ofNullable(user);
if (Optional.isPresent()){
// TODO: do something
}
ifPresent(Consumer<? super T> consumer)
,用法也很简单,如下所示
Optional.ofNullable(user).ifPresent(u->{
// TODO: do something
});
filter(Predicate<? super T> predicate)
public final class Optional<T> {
//省略....
Objects.requireNonNull(predicate);
if (!isPresent())
return this;
else
return predicate.test(value) ? this : empty();
}
Optional<User> user1 = Optional.ofNullable(user).filter(u -> u.getName().length()<6);
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("取值错误");
}
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.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;
}
}
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;
});
}
作者:zjhred
来源:blog.csdn.net/zjhred/article/details/84976734
本文分享自微信公众号 - Java后端(web_resource)。
如有侵权,请联系 support@oschina.cn 删除。
本文参与“OSC源创计划”,欢迎正在阅读的你也加入,一起分享。
相关文章
暂无评论...