java JDK1.8 利用lamdba表达式简化获取值时的空指针处理

简介

一直一以来 java 对 null 处理都是挺麻烦和痛苦的,为了防止 NullPointerException 我们需要做很多 null 检查。
例如:root.getSecond().getThird().getValue() ,为了从 root 获取到 third.value 的值,代码上需要做很多 null 检查

if(root != null && root.getSecond() != null && root.getSecond().getThird() != null){
	return root.getSecond().getThird().getValue();
}

为了简化这些繁琐的操作所以利用 lamdba 表达式写了一个工具类
点击查看工具类代码

使用方法

// 获取值,如果有任何一级为 null 则返回 null
Integer value = NullPointUtil.get(() -> root.getSecond().getThird().getValue());
// 获取值,如果有任何一级为 null 则返回 默认值
Integer value = NullPointUtil.get(() -> root.getSecond().getThird().getValue(), defalutValue);
// 建议使用该方式
Optional<Integer> optional = NullPointUtil.getOptional(() -> root.getSecond().getThird().getValue());
// 判断是否能获取到值
boolean isNull = NullPointUtil.isNull(() -> root.getSecond().getThird().getValue());
boolean nonNull= NullPointUtil.nonNull(() -> root.getSecond().getThird().getValue());

// 判断值是否等于10
if (NullPointUtil.test(() -> root.getSecond().getThird().getValue() == 10)){
}
// 相当于下面的判断
if (root != null && root.getSecond() != null 
				&& root.getSecond().getThird() != null 
                && root.getSecond().getThird().getValue() != null 
                && root.getSecond().getThird().getValue() == 10){
}

// 判断值是否不等于10
if (NullPointUtil.testOrNull(() -> root.getSecond().getThird().getValue() != 10)){
}
// 相当于下面的判断
if (root == null || root.getSecond() == null 
				|| root.getSecond().getThird() == null 
                || root.getSecond().getThird().getValue() == null 
                || root.getSecond().getThird().getValue() != 10){
}

// 判断获取的两个值是否相等
if (NullPointUtil.equals(() -> root1.getSecond().getThird().getValue(), 
					() -> root2.getSecond().getThird().getValue())){
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值