Optional.ofNullable与ifPresent的代码搭配
2022/1/11 23:10:56
本文主要是介绍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 );
}
这篇关于Optional.ofNullable与ifPresent的代码搭配的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-05-15鸿蒙生态设备数量超8亿台
- 2024-05-13TiDB + ES:转转业财系统亿级数据存储优化实践
- 2024-05-09“2024鸿蒙零基础快速实战-仿抖音App开发(ArkTS版)”实战课程已上线
- 2024-05-09聊聊如何通过arthas-tunnel-server来远程管理所有需要arthas监控的应用
- 2024-05-09log4j2这么配就对了
- 2024-05-09nginx修改Content-Type
- 2024-05-09Redis多数据源,看这篇就够了
- 2024-05-09Google Chrome驱动程序 124.0.6367.62(正式版本)去哪下载?
- 2024-05-09有没有大佬知道这种数据应该怎么抓取呀?
- 2024-05-09这种运行结果里的10.100000001,怎么能最快改成10.1?