做项目时,经常会遇到判断null的问题,在之前有Objects.requireNonNull()来解决,java8提供了Optional来解决这个问题,在网上看到一篇讲解Option的博客,阅读后拿来加强自己的记忆。
原博客https://blog.csdn.net/zjhred/article/details/84976734?utm_medium=distribute.pc_relevant_t0.none-task-blog-BlogCommendFromBaidu-1.not_use_machine_learn_pai&depth_1-utm_source=distribute.pc_relevant_t0.none-task-blog-BlogCommendFromBaidu-1.not_use_machine_learn_pai
实战使用:
(1)在函数方法中
以前写法
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("取值错误"); }
JAVA8写法
public String getCity(User user) throws Exception{ return Optional.ofNullable(user) .map(u-> u.getAddress()) .map(a->a.getCity()) .orElseThrow(()->new Exception("取指错误")); }
(2)比如,在主程序中
以前写法
if(user!=null){ dosomething(user); }
JAVA8写法
Optional.ofNullable(user) .ifPresent(u->{ dosomething(u); });
(3)以前写法
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; } }
JAVA8写法
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; }); }