【持续更新中】随笔记录

随笔记录



前言

记录一些看到的方法之类的,记录一下,方便以后取用。


1. 判断属性不为空,用Optional.ofNullable 优雅的写法

//以前写法
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("取指错误"));
}

猜你喜欢

转载自blog.csdn.net/weixin_47410172/article/details/127842897
今日推荐