【java8】java8新特性之Optional

Optional主要是为了解决空指针异常的问题

目录

创建Optional类

of()

 ofNullable()

访问Optional对象的值

get()

orElse()


创建Optional类

of()

Optional<User> opt = Optional.of(user);

由源码可知,参数必须是存在的,不为null的,否则会抛空指针异常

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

 ofNullable()

Optional<User> opt = Optional.ofNullable(user);

如果对象可能为null也可能不为null的时候,可以使用ofNullable()方法。

根据源码,我们可以看到在方法中对value参数做了处理。

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

访问Optional对象的值

get()

Optional<User> opt = Optional.ofNullable(user);
if (opt.isPresent()){
    User u = opt.get();
}

如果user为空直接get的话会报异常,所以我们需要在get之前做判断。使用isPresent进行判断。

    /**
     * Return {@code true} if there is a value present, otherwise {@code false}.
     *
     * @return {@code true} if there is a value present, otherwise {@code false}
     */
    public boolean isPresent() {
        return value != null;
    }

orElse()

orElse()如果有值的话则返回该值,否则返回传递给它的参数值。
User user1 = new User("zxx");
User user2 = new User("lan");
User user = Optional.ofNullable(user1).orElse(user2);
System.out.println(user.getName()); //zxx

        
User user3 = null;
String name = Optional.ofNullable(user3).map(obj->obj.getName()).orElse("lan");
System.out.println(name); //lan

更多方法可以自行了解。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值