2019独角兽企业重金招聘Python工程师标准>>>

import java.util.NoSuchElementException;
import java.util.Objects;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;
import java.util.function.Supplier;/*** 一个容器对象,可能会或可能不会包含一个非空值。* 如果一个值是存在的, {@code isPresent()} will return {@code true} and* {@code get()} will return the value.* @since 1.8*/
public final class Optional<T> {/*** 用于方法empty()*/private static final Optional<?> EMPTY = new Optional<>();/*** 如果非空值,就是该值;如果为空,表示没有值*/private final T value;/*** 私有化空参构造** @implNote 一般只有一个空的实例, {@link Optional#EMPTY},* 每个VM应该存在。*/private Optional() {this.value = null;}/*** 返回一个空的 {@code 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> 无参* @return 返回一个Optional对象 {@code Optional}*/public static<T> Optional<T> empty() {@SuppressWarnings("unchecked")Optional<T> t = (Optional<T>) EMPTY;return t;}/*** 私有化有参构造** @param value 当前值不能为null* @throws NullPointerException 如果值为null,抛出NPE异常*/private Optional(T value) {//校验是否对象是否为空,为空抛出异常,不为空(返回传入的对象)this.value = Objects.requireNonNull(value);/** public static <T> T requireNonNull(T obj) {*    if (obj == null){*       throw new NullPointerException();*    }*    return obj;* }* */}/*** 参数不能为null* @param <T> the class of the value* @param value 必须非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);}/*** 如果传入的值为null,就调用empty()方法,返回一个对象,否则调用of(value)方法,返回一个对象* @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);}/*** 如果存在一个值{ @code Optional},返回值,* 否则 throws {@code NoSuchElementException}.* 此方法不常用*          User user = new User();*         Optional userOptional =   Optional.ofNullable(user);*         Object o1 = userOptional.get();*         //com.shilvfei.web.User@19f2327*         System.out.println(o1);* @return the non-null value held by this {@code Optional}* @throws NoSuchElementException if there is no value present** @see Optional#isPresent()*/public T get() {if (value == null) {throw new NoSuchElementException("No value present");}return value;}/*** 判断值是否为空,为空返回false,不为空返回true*          User user = new User();*         Optional userOptional =   Optional.ofNullable(user);*         //true*         System.out.println(userOptional.isPresent());* @return {@code true} if there is a value present, otherwise {@code false}*/public boolean isPresent() {return value != null;}/*** 如果value != null,调用指定的Consumer实现类中的accept(value)方法,* 否则什么都不做。** @param consumer block to be executed if a value is present* @throws NullPointerException if value is present and {@code consumer} is* null*/public void ifPresent(Consumer<? super T> consumer) {if (value != null)consumer.accept(value);}/*** If a value is present, and the value matches the given predicate,* return an {@code Optional} describing the value, otherwise return an* empty {@code Optional}.** @param predicate a predicate to apply to the value, if present* @return an {@code Optional} describing the value of this {@code Optional}* if a value is present and the value matches the given predicate,* otherwise an empty {@code Optional}* @throws NullPointerException if the predicate is null*/public Optional<T> filter(Predicate<? super T> predicate) {Objects.requireNonNull(predicate);if (!isPresent())return this;elsereturn predicate.test(value) ? this : empty();}public<U> Optional<U> map(Function<? super T, ? extends U> mapper) {//判断对象是否为空Objects.requireNonNull(mapper);//如果value为空,返回Optional对象if (!isPresent())return empty();else {//不为空,返回mapper.apply(value)的值return Optional.ofNullable(mapper.apply(value));}}/*** If a value is present, apply the provided {@code Optional}-bearing* mapping function to it, return that result, otherwise return an empty* {@code Optional}.  This method is similar to {@link #map(Function)},* but the provided mapper is one whose result is already an {@code Optional},* and if invoked, {@code flatMap} does not wrap it with an additional* {@code Optional}.** @param <U> The type parameter to the {@code Optional} returned by* @param mapper a mapping function to apply to the value, if present*           the mapping function* @return the result of applying an {@code Optional}-bearing mapping* function to the value of this {@code Optional}, if a value is present,* otherwise an empty {@code Optional}* @throws NullPointerException if the mapping function is null or returns* a null result*/public<U> Optional<U> flatMap(Function<? super T, Optional<U>> mapper) {Objects.requireNonNull(mapper);if (!isPresent())return empty();else {return Objects.requireNonNull(mapper.apply(value));}}/*** 判断value是否为空,为空返回other,不为空返回value {@code 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;}/*** 判断value是否为空,为空调用指定方法,并返回该调用方法返回的结果,不为空返回value的值** @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();}/*** Return the contained value, if present, otherwise throw an exception* to be created by the provided supplier.** @apiNote A method reference to the exception constructor with an empty* argument list can be used as the supplier. For example,* {@code IllegalStateException::new}** @param <X> Type of the exception to be thrown* @param exceptionSupplier The supplier which will return the exception to* be thrown* @return the present value* @throws X if there is no value present* @throws NullPointerException if no value is present and* {@code exceptionSupplier} is null*/public <X extends Throwable> T orElseThrow(Supplier<? extends X> exceptionSupplier) throws X {if (value != null) {return value;} else {throw exceptionSupplier.get();}}@Overridepublic boolean equals(Object obj) {if (this == obj) {return true;}if (!(obj instanceof Optional)) {return false;}Optional<?> other = (Optional<?>) obj;return Objects.equals(value, other.value);}@Overridepublic int hashCode() {return Objects.hashCode(value);}@Overridepublic String toString() {return value != null? String.format("Optional[%s]", value): "Optional.empty";}
}

转载于:https://my.oschina.net/u/3568600/blog/1922705

java8 Optional源码相关推荐

  1. Java8 HashMap源码分析

    前言 今天,我们主要来研究一下在Java8中HashMap的数据结构及一些重要方法的具体实现.       研究HashMap的源代码之前,我们首先来研究一下常用的三种数据结构:数组.链表和红黑树. ...

  2. Java8 ThreadLocal 源码分析

    可参考文章: Java8 IdentityhashMap 源码分析 IdentityhashMap 与 ThreadLocalMap 一样都是采用线性探测法解决哈希冲突,有兴趣的可以先了解下 Iden ...

  3. Java8 Hashtable 源码阅读

    一.Hashtable 概述 Hashtable 底层基于数组与链表实现,通过 synchronized 关键字保证在多线程的环境下仍然可以正常使用.虽然在多线程环境下有了更好的替代者 Concurr ...

  4. 和我一起读Java8 LinkedList源码

    书接上一篇ArrayList源码解析,这一节继续分析LinkedList在Java8中的实现,它同样实现了List接口,不过由名字就可以知道,内部实现是基于链表的,而且是双向链表,所以Linked L ...

  5. Java8 EnumSet 源码简单分析

    一.EnumSet 概述 EnumSet 是一个用于存储枚举类型的 set 集合,一般的 set 集合底层都是使用对应的 map 实现的,但 EnumSet 是个特例,它底层使用一个 long 类型的 ...

  6. Java8 EnumMap 源码分析

    一.EnumMap 概述 EnumMap 是一个用于存储 key 为枚举类型的 map,底层使用数组实现(K,V 双数组).下面是其继承结构: public class EnumMap<K ex ...

  7. Java8 PriorityBlockingQueue源码分析

    在看这篇总结之前,建议大家先熟悉一下 PriorityQueue,这里主要介绍 PriorityBlockingQueue 一些特殊的性质,关于优先级队列的知识不作着重介绍,因为过程与 Priorit ...

  8. Java8 IdentityHashMap 源码分析

    在讲这个数据结构之前,我们先来看一段代码: public static void main(String[] args) {IdentityHashMap<String, Integer> ...

  9. Java8 CountDownLatch 源码分析

    一.CountDownLatch 概述 1.1 什么是 CountDLatch 闭锁(CountDownLatch)是 java.util.concurrent 包下的一种同步工具类.闭锁可以用来确保 ...

最新文章

  1. 异步绘制Cell解决列表快速滚动造成的卡顿
  2. 时间戳显示为多少分钟前,多少天前的JS处理,JS时间格式化,时间戳的转换
  3. 03-25实验一、命令解释程序的编写
  4. 使用Redis实现在线点赞系统
  5. bootstrap的栅格布局与两列布局结合使用
  6. python numpy 中 np.mean(a) 跟 a.mean() 的区别
  7. HTTP/3 来啦,你还在等什么?赶紧了解一下
  8. 2020 操作系统第三天复习(知识点总结)
  9. Scala元组数据的访问
  10. 80070583类不存在_原创 | 类应该是匀称和均匀的
  11. Re(正则表达式)库入门
  12. React开发(152):注意替换路径
  13. urllib库的学习-发起请求urlopen-下载资源urlretrleve
  14. C语言printf函数
  15. 行内元素(内联元素)与块级元素
  16. SLAM++:面向对象的同时定位与建图系统(2013-CVPR)
  17. 神经网络的Dropout的理解
  18. 已知直角三角形的周长,求可以构成三角形的情况
  19. 计算机网络实验一:网线制作和局域网组建lab1 report
  20. Linux nm命令详解

热门文章

  1. 网站设计中程序员和美工的配合问题
  2. Vue实现跑马灯效果以及封装为组件发布
  3. 技术的价值--从实验到企业实施的关键性思想
  4. 写一个简单的实时互动小游戏
  5. 《深入react技术栈》学习笔记(一)初入React世界
  6. python--列表list
  7. Stooge排序与Bogo排序算法
  8. flask中的请求上下文
  9. PDF 补丁丁 0.4.1.688 测试版发布(请务必用其替换 682 测试版)
  10. Extjs DateField onchange