Java-SE-8之Optional分析

Scroll Down

Optional

先准备一个基类,用于模拟业务开发过程中的entity

    @Data
    @ToString
    @AllArgsConstructor
    @NoArgsConstructor
    class Student{
        private String name;
        private int age;
        private String message;
    }
isPresent
       /**
         * 模拟该student对象是从远端拉取回来,
         */
        Function<Integer, Optional<Student>> remote=x->{
            try {
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if (x>20){
                Student student= new Student("阿Q",x,"鲁迅的笔杆子");
                return  Optional.ofNullable(student);
            }else {
                return  Optional.empty();
            }
        };
        /**
         * 最傻屌的Optional使用方式,这属于说不明白Optional是个干啥的选手。基本一问就懵。
         * 只知道Optional是在Java SE 8中用于避免NullPointerException,这和我们使用原来的null!=student有什么区别。
         * 怎么做到高逼格的使用Optional,在内心中要做到把isPresent方法设置为private修饰。
         */
        Optional<Student> student=remote.apply(23);
        if (student.isPresent()){
            System.out.println("Student 存在"+student.get());
        }else {
            System.out.println("Student 不存在"+student.get());
        }
of
 	  /**
         *Optional.of针对绝对不为null的对象进行包装,通过map进行一系列操作;
         * 如果添加对象为null则会抛出NullPointerException
         */
        Student student1=new Student();
        System.out.println(Optional.of(student1)
                .map(x->{x.setName("李强");x.setAge(1);x.setMessage("李强出生了"+x.getAge()+"岁");return x; })
                .map(x->{ x.setAge(18);x.setMessage(x.message+"|长大了"+x.getAge()+"岁");return x; })
                .map(x->{x.setAge(28);x.setMessage(x.message+"|结婚了"+x.getAge()+"岁");return x; })
                .map(x->{x.setAge(69);x.setMessage(x.message+"|死亡了"+x.getAge()+"岁");return x; })
                .orElse(null));
ofNullable
	   /**
         * 初始数据就为null 则给定默认值
         * ofNullable 比较容错性高一些,
         * 如果传入的是null则返回的是Optional.EMPTY;
         * 如果该对象不是null则内部调用Optional.of(t)
         * <pre>
         *     public static <T> Optional<T> ofNullable(T value) {
         *          return value == null ? empty() : of(value);
         *      }
         * </pre>
         */
        Student student2=null;
        System.out.println(Optional.ofNullable(student2)
                .map(x->{ x.setName("李强");return x; })
                .orElse(new Student("李强",18,"李强逃课了")));
map
 	  /**
         *针对附属数据的处理如果获取失败,则给定默认值
         */
        Student student3=new Student("李强",18,"李强签到了");
        System.out.println(Optional.ofNullable(student3)
                .map(x->{x.setAge(28);x.setMessage("没有签退逃跑了");return null; })
                .orElseGet(()-> new Student("李大强",18,"李强逃跑了找李大强冒充一下签退")));
filter
 	  /**
         * 执行过滤
         */
        Student student4=new Student("李强",28,"李强来面试了");
        System.out.println(Optional.ofNullable(student4)
                .filter(x->x.getAge()>28)
                .orElseGet(()-> new Student("补录李小强",27,"李强年龄太大了 不适合")));