Optional.ofNullable与ifPresent的代码搭配
如果前面的判断不是null,则进行设置值。 一笔完成完美 ,额报错了,不适合多层直接调用。如果能接住就好了。
Optional.ofNullable(skuMap.get(esteem.getRelationId()).getSpuId()).ifPresent(secondaryMenuItemsVo::setRelationId);
public void OptTest(User user) {
 // 第一种方式:存在空指针的风险,只要与一个对象为空就会空指针
        String countryName = user.getAddress().getCountry().getCountryName();
        System.out.println( "第一种方式:" + countryName );
        // 第二种方式:各种if判断避免了空指针,但是if层级太深,代码冗长
        if (user != null) {
            Address address = user.getAddress();
            if (address != null) {
                Country country = address.getCountry();
                if (country != null) {
                    String couName = country.getCountryName();
                    System.out.println( "第二种方式:" + couName );
                }
            }
        }
        // 第三种方式:代码简洁,避免空指针,武林那一步为空都会返回默认值
        String counName = Optional.ofNullable( user )
                .map( User::getAddress )
                .map( Address::getCountry )
                .map( Country::getCountryName )
                .orElse( "china" );
        System.out.println( "第三种方式:" + counName );
        // 第三种方式:代码简洁,避免空指针,武林那一步为空都会返回自定义异常
        String countryNameEx = Optional.ofNullable( user )
                .map( User::getAddress )
                .map( Address::getCountry )
                .map( Country::getCountryName )
                .orElseThrow( () -> new RuntimeException( "countryId is null" ) );
        System.out.println( "第四种方式:" + countryNameEx );
    }
---------------------------------------------------------------------------
国之殇,未敢忘!
南京大屠杀!
731部队!
(有关书籍《恶魔的饱食》)以及核污染水排海等一系列全无人性的操作,购买他们的食品和为它们提供帮助只会更加变本加厉的害你,呼吁大家不要购买日本相关产品
昭昭前事,惕惕后人
吾辈当自强,方使国不受他人之侮!
---------------------------------------------------------------------------
作者:三号小玩家
出处:https://www.cnblogs.com/q1359720840/
版权声明:本作品采用知识共享署名-非商业性使用-禁止演绎 2.5 中国大陆许可协议进行许可。 版权信息
 
                    
                     
                    
                 
                    
                
 
 
                
            
         
         浙公网安备 33010602011771号
浙公网安备 33010602011771号