经常在程序中出现 java.lang.NullPointerException  为了避免  报错,总是要进行一些 是否为null 的if else 判断 ,1.8 可以使用optional 类 来简化处置
   optional :A container object which may or may not contain a non-null value.:可能包含也可能不包含非空值的容器对象。

  • 既然optional 是一个容器对象,那就应该先创建该 对象 才能调用该对象的一些方法 创建optional的方式:
  1. 调用Optional静态方法.empty()  来创建一个optional 容器对象

    /**
    * 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;
    }
    public static void testOptional() {
    Optional<Object> empty = Optional.empty();
    }
  2. optional 的构造函数 权限是private 的 所以 不能直接通过构造函数的方法 生成该对象,调用静态方法of(T t) 可以创建一个指定参数的optional  
    /**
    * 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);
    }
    public static void testOptional() {
    // 使用 Optional.empty() 创建 Optional 对象
    Optional<Object> empty = Optional.empty();
    // 私有化构造函数 不能直接 创建
    // Optional<User> optional = new Optional(new User());
    // 使用 Optional.of() 创建 Optional 对象
    Optional<User> optional = Optional.of(new User());
    }
  3. Opional 有一个静态方法 ofNullable(T t)可以 根据你传入的值 来 来判断调用 Optional的无参构造方法还是调用 optional 的有参构造方法 如果是null 则调用 empty() 为空 则调用 of(T t) 方法
    /**
    * 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);
    }
    public static void testOptional() {
    // 使用 Optional.empty() 创建 Optional 对象
    Optional<Object> empty = Optional.empty();
    // 私有化构造函数 不能直接 创建
    // Optional<User> optional = new Optional(new User());
    // 使用 Optional.of() 创建 Optional 对象
    Optional<User> optional = Optional.of(new User());
    //使用 Optional.ofNullable() 创建 Optional 对象
    Optional<Object> ofNullable = Optional.ofNullable(null);
    }
  • 以上三种方法 都可以创建一个Optional 对象,如何使用该对象的方法
  1. 获取 optional 的值  调用 get()方法 如果 为null 则抛出异常

        /**
    * If a value is present in this {@code Optional}, returns the value,
    * otherwise throws {@code NoSuchElementException}.
    *
    * @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;
    }

  2. 检测 optional的值是否为空 如果 为空 则 false

        /**
    * 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;
    }
    package lambda.stream;
    
    import java.util.Optional;
    
    /**
    * @author 作者:cb
    * @version 创建时间:2019年1月14日 上午11:12:12
    *
    */
    public class OptionalDemo {
    public static void main(String[] args) {
    testIsPresent();
    } public static void testIsPresent() {
    Optional<User> optional = Optional.ofNullable(new User());
    boolean flag = optional.isPresent();
    System.out.println(flag);
    optional = Optional.ofNullable(null);
    flag = optional.isPresent();
    System.out.println(flag);
    }
    }
    true
    false
  3. optional 可以根据  ifPresent 来对 值T  进行 自身的处理 
        /**
    * If a value is present, invoke the specified consumer with the value,
    * otherwise do nothing.
    *
    * @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);
    }
    public class OptionalDemo {
    public static void main(String[] args) {
    testIfPresent();
    // testIsPresent();
    } public static void testIfPresent() {
    Optional<User> optional = Optional.ofNullable(new User());
    optional.ifPresent((age) -> age.setAge(100));
    System.out.println(optional.get().getAge()); }
    100
  4. 检测一个用户的名称是否 满足 特定条件的时候 ,optional 的filter 方法 
        /**
    * 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;
    else
    return predicate.test(value) ? this : empty();
    }
    package lambda.stream;
    
    import java.util.Arrays;
    import java.util.List;
    import java.util.Optional;
    import java.util.stream.Collectors; /**
    * @author 作者:cb
    * @version 创建时间:2019年1月14日 上午11:12:12
    *
    */
    public class OptionalDemo {
    public static void main(String[] args) {
    testFilter();
    // testIfPresent();
    // testIsPresent();
    } public static void testFilter() {
    Optional<User> ofNullable = Optional.ofNullable(new User("Tom", 15));
    Optional<User> filter = ofNullable.filter(user -> user.getAge() == 15);
    }
    User [name=Tom, age=15]

    如果 没有满足 条件是 15的  返回值打印 报错

    package lambda.stream;
    
    import java.util.Arrays;
    import java.util.List;
    import java.util.Optional;
    import java.util.stream.Collectors; /**
    * @author 作者:cb
    * @version 创建时间:2019年1月14日 上午11:12:12
    *
    */
    public class OptionalDemo {
    public static void main(String[] args) {
    testFilter();
    // testIfPresent();
    // testIsPresent();
    } public static void testFilter() {
    Optional<User> ofNullable = Optional.ofNullable(new User("Tom", 25));
    Optional<User> filter = ofNullable.filter(user -> user.getAge() == 15);
    Exception in thread "main" java.util.NoSuchElementException: No value present
    at java.util.Optional.get(Optional.java:135)
    at lambda.stream.OptionalDemo.testFilter(OptionalDemo.java:25)
    at lambda.stream.OptionalDemo.main(OptionalDemo.java:16)
  5. Optional 对象中map的使用:返回 User对象的 name属性
        /**
    * If a value is present, apply the provided mapping function to it,
    * and if the result is non-null, return an {@code Optional} describing the
    * result. Otherwise return an empty {@code Optional}.
    *
    * @apiNote This method supports post-processing on optional values, without
    * the need to explicitly check for a return status. For example, the
    * following code traverses a stream of file names, selects one that has
    * not yet been processed, and then opens that file, returning an
    * {@code Optional<FileInputStream>}:
    *
    * <pre>{@code
    * Optional<FileInputStream> fis =
    * names.stream().filter(name -> !isProcessedYet(name))
    * .findFirst()
    * .map(name -> new FileInputStream(name));
    * }</pre>
    *
    * Here, {@code findFirst} returns an {@code Optional<String>}, and then
    * {@code map} returns an {@code Optional<FileInputStream>} for the desired
    * file if one exists.
    *
    * @param <U> The type of the result of the mapping function
    * @param mapper a mapping function to apply to the value, if present
    * @return an {@code Optional} describing the result of applying a 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
    */
    public<U> Optional<U> map(Function<? super T, ? extends U> mapper) {
    Objects.requireNonNull(mapper);
    if (!isPresent())
    return empty();
    else {
    return Optional.ofNullable(mapper.apply(value));
    }
    }
    package lambda.stream;
    
    import java.util.Arrays;
    import java.util.List;
    import java.util.Optional;
    import java.util.stream.Collectors; /**
    * @author 作者:cb
    * @version 创建时间:2019年1月14日 上午11:12:12
    *
    */
    public class OptionalDemo {
    public static void main(String[] args) {
    testMap();
    // testIfPresent();
    // testIsPresent();
    } public static void testMap() {
    Optional<User> ofNullable = Optional.ofNullable(new User("Tom", 25));
    Optional<String> map = ofNullable.map(user -> user.getName());
    System.out.println(map.get());
    }

    结果:

    Tom
  6. Optional 的orElse 方法 
        /**
    * Return the value if present, otherwise return {@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;
    }
    package lambda.stream;
    
    import java.util.Arrays;
    import java.util.List;
    import java.util.Optional;
    import java.util.stream.Collectors; /**
    * @author 作者:cb
    * @version 创建时间:2019年1月14日 上午11:12:12
    *
    */
    public class OptionalDemo {
    public static void main(String[] args) {
    testOrelse();
    // testIfPresent();
    // testIsPresent();
    } public static void testOrelse() {
    Optional<User> ofNullable = Optional.ofNullable(null);
    User orElse = ofNullable.orElse(new User("Tom", 35));
    System.out.println(orElse);//结果:User [name=Tom, age=35]
    }
    package lambda.stream;
    
    import java.util.Arrays;
    import java.util.List;
    import java.util.Optional;
    import java.util.stream.Collectors; /**
    * @author 作者:cb
    * @version 创建时间:2019年1月14日 上午11:12:12
    *
    */
    public class OptionalDemo {
    public static void main(String[] args) {
    testOrelse();
    // testIfPresent();
    // testIsPresent();
    } public static void testOrelse() {
    Optional<User> ofNullable = Optional.ofNullable(new User("jack", 45));
    User orElse = ofNullable.orElse(new User("Tom", 35));
    System.out.println(orElse);//结果:User [name=jack, age=45] }
  7. Optional 的orElseGet方法  方法用处和orElseGet 一样只是 传递的参数 类型 不一样 一个是T  一个 function类型的接口
        /**
    * Return the value if present, otherwise invoke {@code other} and return
    * the result of that invocation.
    *
    * @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();
    }
    package lambda.stream;
    
    import java.util.Arrays;
    import java.util.List;
    import java.util.Optional;
    import java.util.stream.Collectors; /**
    * @author 作者:cb
    * @version 创建时间:2019年1月14日 上午11:12:12
    *
    */
    public class OptionalDemo {
    public static void main(String[] args) {
    testOrElseGet();
    // testIfPresent();
    // testIsPresent();
    } public static void testOrElseGet() {
    Optional<User> ofNullable = Optional.ofNullable(new User("jack", 45));
    User orElseGet = ofNullable.orElseGet(() -> new User("Tom", 35));
    System.out.println(orElseGet);// 结果:User [name=Tom, age=35] }
  8. optional 的flatMap使用(扁平化):

java1.8新特性(optional 使用)的更多相关文章

  1. java1.8新特性之stream流式算法

    在Java1.8之前还没有stream流式算法的时候,我们要是在一个放有多个User对象的list集合中,将每个User对象的主键ID取出,组合成一个新的集合,首先想到的肯定是遍历,如下: List& ...

  2. JDK1.8新特性——Optional类

    JDK1.8新特性——Optional类 摘要:本文主要学习了JDK1.8新增加的Optional类. 部分内容来自以下博客: https://www.cnblogs.com/1ning/p/9140 ...

  3. Java1.8新特性 - Stream流式算法

    一. 流式处理简介   在我接触到java8流式数据处理的时候,我的第一感觉是流式处理让集合操作变得简洁了许多,通常我们需要多行代码才能完成的操作,借助于流式处理可以在一行中实现.比如我们希望对一个包 ...

  4. Stream:java1.8新特性

    原 Stream:java1.8新特性 2017年08月01日 18:15:43 kekeair-zhang 阅读数:392 标签: streamjava1-8新特性 更多 个人分类: 日记 版权声明 ...

  5. JAVA8新特性Optional,非空判断

    Optional java 的 NPE(Null Pointer Exception)所谓的空指针异常搞的头昏脑涨, 有大佬说过 "防止 NPE,是程序员的基本修养." 但是修养归 ...

  6. java1.8新特性(一)

    一直在更新java 版本,原来也没有关注java版本的变化 引入的一些新的api  引起注意的还是  关于一些并发包的使用,那时候才对每个版本的特性 去了解了一下,虽然 不一定都用上了,但是不管学习什 ...

  7. java1.8新特性整理(全)

    版权声明:本文为博主原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明. 本文链接:https://blog.csdn.net/yitian_66/article/deta ...

  8. Java8 新特性 Optional 类

    Optional 类的简介   Optional类的是来自谷歌Guava的启发,然后就加入到Java8新特性中去了.Optional类主要就是为子决解价值亿万的错误,空指针异常.   Optional ...

  9. java1.7新特性:try-with-resources

    转载:https://blog.csdn.net/fanxiaobin577328725/article/details/53067163 首先看代码: import org.junit.Test; ...

  10. Java8新特性——Optional

    前言 在开发中,我们常常需要对一个引用进行判空以防止空指针异常的出现.Java8引入了Optional类,为的就是优雅地处理判空等问题.现在也有很多类库在使用Optional封装返回值,比如Sprin ...

随机推荐

  1. 20155208徐子涵 2016-2017-2 《Java程序设计》第9周学习总结

    20155208徐子涵 2016-2017-2 <Java程序设计>第9周学习总结 教材学习内容总结 第十六章 整合数据库 16.1 JDBC入门 撰写应用程序是利用通信协议对数据库进行指 ...

  2. LG5901 【模板】欧拉定理

    题意 题目描述 给你三个正整数,$a,m,b$,你需要求: $a^b \mod m$ 输入输出格式 输入格式: 一行三个整数,$a,m,b$ 输出格式: 一个整数表示答案 输入输出样例 输入样例#1: ...

  3. vue全家桶+Koa2开发笔记(4)--redis

    redis用来在服务器端存放session 1 安装redis    brew install redis 启动redis   redis-server 2 安装两个中间件  npm i koa-ge ...

  4. c# 多线程 读写分离

    class Program { private static ReaderWriterLockSlim _LockSlim = new ReaderWriterLockSlim(); private ...

  5. 【点击项目属性】Target runtime Apache Tomcat v7.0 is not defined

    这个项目是去年用同一个eclipse做的,但是今年原封不动导入的时候,确发现这个东西 tomcat选成我们本地的tomcat8就可以了 泼菲解决.

  6. centos7.0之vsftpd随笔

    yum install vsftpd -f安装vsftpd软件 systemctl start vsftpd 默认ftp目录为/var/ftp/,该文件夹下有pub文件夹 iptables -F 防火 ...

  7. madlib 集成 hasura graphql-engine 试用

    madlib 可以让我们直接在sql 中进行机器学习,集成了强大的sql 能力,以及分析能力,后边会尝试 集成graphql engine ,让功能更强大 docker 镜像准备 使用了一个别人的写好 ...

  8. 使用ipns 解决ipfs 内容更新的问题

    ipds 可以使用dnslink 解决域名访问的问题,但是内容变更我们就会有新的hashid 解决方法我们可以使用ipns ,同时解决dnslink 解决域名的问题 环境准备 docker-compo ...

  9. C# to IL 10 Exception Handling(异常处理)

    Exception handling in IL is a big let down. We expected a significant amount of complexity,but were ...

  10. 机器学习 - 开发环境安装pycharm + pyspark + spark集成篇

    AS WE ALL KNOW,学机器学习的一般都是从python+sklearn开始学,适用于数据量不大的场景(这里就别计较“不大”具体指标是啥了,哈哈) 数据量大了,就需要用到其他技术了,如:spa ...