1. 程式人生 > 實用技巧 >java8-Optional解決判斷Null的問題

java8-Optional解決判斷Null的問題

  做專案時,經常會遇到判斷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;
                   });
}