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 );
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM