java8:Optional.ofNullable的使用

-- 

Optional类是Java8为了解决null值判断问题,使用Optional类可以避免显式的null值判断(null的防御性检查),避免null导致的NPE(NullPointerException)。

示例:

public static void main(String[] args) {
	TestDemo testDemo = new TestDemo();
	getCount(testDemo);
}

private static void getCount(TestDemo testDemo) {
	//if判断:判断好多层
	int count1 = 1;
	if(testDemo != null){
		if(testDemo.getCount() != null){
			count1 = testDemo.getCount();
		}
	}
	System.out.println(count1);
	
	//三目运算符:嵌套层数深,可读性不好
	int count2 = testDemo != null ? (testDemo.getCount() != null ? testDemo.getCount() : 1) : 1;
	System.out.println(count2);
	
	//Java8-Optional:优雅,可读性较好
	int count3 = Optional.ofNullable(testDemo).map(item -> item.getCount()).orElse(1);
	System.out.println(count3);
}

private static class TestDemo {

	private Integer count;

	public Integer getCount() {
		return count;
	}

	public void setCount(Integer count) {
		this.count = count;
	}
}


源码:

/**
 * Returns an {@code Optional} describing the specified value, if non-null,
 * otherwise returns an empty {@code Optional}.
 *
 * @param <T> the class of the value
 * @param value the possibly-null value to describe
 * @return an {@code Optional} with a present value if the specified value
 * is non-null, otherwise an empty {@code Optional}
 */
public static <T> Optional<T> ofNullable(T value) {
	return value == null ? empty() : of(value);
}
/**
 * Returns an empty {@code Optional} instance.  No value is present for this
 * Optional.
 *
 * @apiNote Though it may be tempting to do so, avoid testing if an object
 * is empty by comparing with {@code ==} against instances returned by
 * {@code Option.empty()}. There is no guarantee that it is a singleton.
 * Instead, use {@link #isPresent()}.
 *
 * @param <T> Type of the non-existent value
 * @return an empty {@code Optional}
 */
public static<T> Optional<T> empty() {
	@SuppressWarnings("unchecked")
	Optional<T> t = (Optional<T>) EMPTY;
	return t;
}
/**
 * Returns an {@code Optional} with the specified present non-null value.
 *
 * @param <T> the class of the value
 * @param value the value to be present, which must be non-null
 * @return an {@code Optional} with the value present
 * @throws NullPointerException if value is null
 */
public static <T> Optional<T> of(T value) {
	return new Optional<>(value);
}


————————————————
版权声明:本文为CSDN博主「程序小白-M」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/zym_1321/article/details/107769743

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值