Java中Optional类及orElse方法详解

 更新时间:2022年08月25日 15:45:31   作者:按时吃饭并不难  
这篇文章主要为大家介绍了Java中Optional类及orElse()方法详解,有需要的朋友可以借鉴参考下,希望能够有所帮助,祝大家多多进步,早日升职加薪

引言

为了让我更快的熟悉代码,前段时间组长交代了一个小任务,大致就是让我整理一下某个模块中涉及的 sql,也是方便我有目的的看代码,也是以后方便他们查问题(因为这个模块,涉及的判断很多,所以之前如果 sql 出错了,查问题比较繁琐)。

昨天算是基本完成了,然后今天组长就让给我看一个该模块的缺陷,由于刚对该模块进行过整理,所以还算清晰......看代码过程中,看到一些地方进行判空时都用到了 orElse() 方法,之前没怎么用过,熟悉一下......

Java 中的 Optional 类

Optional 类是 Java8 为了解决 NULL 值判断等问题提出的。使用 Optional 类可以避免显式的判断 NULL 值(NULL 的防御性检查),避免某一处因为出现 NULL 而导致的 NPE(NullPointerException)。

ofNullable() 方法

/**
 * A container object which may or may not contain a non-null value.
 * If a value is present, {@code isPresent()} will return {@code true} and
 * {@code get()} will return the value.
 */
 public final class Optional<T> {

    /**
     * Common instance for {@code empty()}.
     */
    private static final Optional<?> EMPTY = new Optional<>(); //执行Optional的无参构造
    
	//无参构造
	private Optional() {
        this.value = null;
    }
    //有参构造
    private Optional(T value) {
        this.value = Objects.requireNonNull(value);
    }
    /**
     * Returns an {@code Optional} describing the specified value, if non-null,
     * otherwise returns an empty {@code Optional}.
     * 如果value不是null, 返回它自己本身, 是空, 则执行empty(), 返回null
     *
     * @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.
     * 当value是空时, 返回Optional<T>对象
     *
     * @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;  //由第一行代码可知, EMPTY是一个无参Optional对象
        return t;
    }
   
    /**
     * Returns an {@code Optional} with the specified present non-null value.
     * 返回不等于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);  //执行Optional的有参构造
    }
 }

从源码中可以看出来,ofNullable() 方法做了 NULL 值判断,所以我们可以直接调用该方法进行 NULL 值判断,而不用自己手写 NULL 值判断。

orElse() 方法

    /**
     * Return the value if present, otherwise return {@code other}.
     * 如果值存在(即不等于空), 返回值本身, 如果等于空, 就返回orElse()方法的参数other.
     *
     * @param other the value to be returned if there is no value present, may
     * be null
     * @return the value, if present, otherwise {@code other}
     */
    public T orElse(T other) {
        return value != null ? value : other;
    }

从源码中可以看出,调用 orElse() 方法时,当值为 NULL 值,返回的是该方法的参数;当值不为 NULL 时,返回值本身。

案例

Optional.ofNullable(scRespDTO.getMsgBody().getSuccess()).orElse(false);

上述案例中,如果 ofNullable() 方法执行结果不为 NULL,则返回 scRespDTO.getMsgBody().getSuccess() 的值;

如果 ofNullable() 方法的执行结果是 NULL,则返回 false,即,orElse() 方法的参数。

orElseGet() 方法

    /**
     * Return the value if present, otherwise invoke {@code other} and return
     * the result of that invocation.
     * 值如果存在(即不为空), 返回值本身, 如果不存在, 则返回实现了Supplier接口的对象. 
     * Supplier接口就只有一个get()方法. 无入参,出参要和Optional的对象同类型.
     *
     * @param other a {@code Supplier} whose result is returned if no value
     * is present
     * @return the value if present otherwise the result of {@code other.get()}
     * @throws NullPointerException if value is not present and {@code other} is
     * null
     */
    public T orElseGet(Supplier<? extends T> other) {
        return value != null ? value : other.get();
    }

从源码中可以看出来,调用 orElseGet() 方法时,如果值为 NULL,返回的是实现了 Supplier 接口的对象的 get() 值;

如果值不为 NULL,则返回值本身。

案例

System.out.println(Optional.ofNullable("努力成为一名更优秀的程序媛").orElseGet(()->"你不够优秀"));
System.out.println(Optional.ofNullable(null).orElseGet(()->"你没有努力"));  

orElseGet() 可以传入一个supplier接口,里面可以花样实现逻辑。

上述案例中,第一句,ofNullable() 不为 NULL,就输出"努力成为一名更优秀的程序媛",反之,则输出"你不够优秀";

第二句,ofNullable() 为 NULL, 输出 "你没有努力"。

orElse() 与 orElseGet() 之间的区别

注意

orElse() 与 orElseGet() 两者之间是 有区别 的。虽然当值为 NULL 时,orElse() 与 orElseGet() 都是返回方法的参数,但区别就是:orElse() 方法返回的是参数本身,而 orElseGet() 方法并不是直接返回参数本身,而是返回 参数的 get() 值,且 该参数对象必须实现 Supplier 接口(该接口为函数式接口)。这就使得 orElseGet() 方法更加灵活。

简单做了一下 Java 中 Optional 类以及其中的 orElse() 方法 与 orElseGet() 方法相关的内容,以前没有了解过。文中显然引入了许多源码,也是为了方便理解不是? :)

以上就是Java中Optional类及orElse()方法详解的详细内容,更多关于Java Optional类 orElse()方法的资料请关注脚本之家其它相关文章!

相关文章

  • java基于swing实现的五子棋游戏代码

    java基于swing实现的五子棋游戏代码

    这篇文章主要介绍了java基于swing实现的五子棋游戏代码,主要涉及图形界面与数组的用法,有不错的参考借鉴价值,需要的朋友可以参考下
    2014-11-11
  • Java 项目连接并使用 SFTP 服务的示例详解

    Java 项目连接并使用 SFTP 服务的示例详解

    SFTP是一种安全的文件传输协议,是SSH(Secure Shell)协议的一个子协议,设计用于加密和保护文件传输的安全性,这篇文章主要介绍了Java 项目如何连接并使用 SFTP 服务的示例详解,需要的朋友可以参考下
    2025-01-01
  • java字符串常用操作方法(查找、截取、分割)

    java字符串常用操作方法(查找、截取、分割)

    今天小编就为大家分享一篇java字符串常用操作方法(查找、截取、分割),具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧
    2018-07-07
  • Jsoup解析html实现招聘信息查询功能

    Jsoup解析html实现招聘信息查询功能

    这篇文章主要为大家详细介绍了Jsoup解析html实现招聘信息查询功能,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2017-04-04
  • Java8中使用一行代码读取文件

    Java8中使用一行代码读取文件

    这篇文章主要介绍了Java8中使用一行代码读取文件,要注意,本文介绍的方法不适合读取很大的文件,因为可能存在内存空间不足的问题,需要的朋友可以参考下
    2015-03-03
  • mybatis中foreach报错:_frch_item_0 not found的解决方法

    mybatis中foreach报错:_frch_item_0 not found的解决方法

    这篇文章主要给大家介绍了mybatis中foreach报错:_frch_item_0 not found的解决方法,文章通过示例代码介绍了详细的解决方法,对大家具有一定的参考学习价值,需要的朋友们下面来一起看看吧。
    2017-06-06
  • Springboot结合Flowable实现工作流开发

    Springboot结合Flowable实现工作流开发

    本文主要介绍了Springboot结合Flowable实现工作流开发,文中通过示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-01-01
  • java swing实现简单计算器界面

    java swing实现简单计算器界面

    这篇文章主要为大家详细介绍了java swing实现简单计算器界面,文中示例代码介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2022-04-04
  • 快速排序算法原理及java递归实现

    快速排序算法原理及java递归实现

    快速排序 对冒泡排序的一种改进,若初始记录序列按关键字有序或基本有序,蜕化为冒泡排序。使用的是递归原理,在所有同数量级O(n longn) 的排序方法中,其平均性能最好。就平均时间而言,是目前被认为最好的一种内部排序方法
    2014-01-01
  • 手把手教你用Java给暗恋对象发送一份表白邮件

    手把手教你用Java给暗恋对象发送一份表白邮件

    随着我们学习java的深入,也渐渐发现了它的一些乐趣,比如发送邮件,下面这篇文章主要给大家介绍了关于如何利用Java给暗恋对象发送一份表白邮件的相关资料,需要的朋友可以参考下
    2021-11-11

最新评论