详细分析Java中的Optional类以及应用场景

参看链接:

  • https://blog.csdn.net/weixin_47872288/article/details/135895605
  • https://blog.csdn.net/weixin_45187434/article/details/131795511
  • https://blog.csdn.net/cxkjntm123/article/details/135206065

验证代码

package com.zs.common.optional;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.util.Optional;

/**
 * @author zs
 * @date 2024/6/28 16:56
 */
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
public class Student {

    /**阿里java开发规范,定义为包装类型,基础类型会初识化为0,Integer没赋值为null*/
    private Integer age;

    private String name;

    private Car car;

    public Optional<Car> getOptionalCar() {

        Insurance lisi = Insurance.builder().name("lisi").build();
        Car car1 = Car.builder().insurance(lisi).build();
        return Optional.ofNullable(car1);
    }
}

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
class Car {

    private Insurance insurance;

    public Optional<Insurance> getOptionalInsurance() {

        Insurance insurance = Insurance.builder().name("wangwu").build();
        return Optional.ofNullable(insurance);
    }
}

@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
class Insurance {

    private String name;

}

 class Test {

    static Student getNullStudent(){

        return null;

    }

     static Student getNotNullStudentAge18(){

        return Student.builder().age(18).build();

     }

     static Student getNotNullStudentAgeIsNull(){

         return Student.builder().build();

     }

     static Student getAllStudent(){

         Insurance zhangsan = Insurance.builder().name("zhangsan").build();
         Car car = Car.builder().insurance(zhangsan).build();
         Student student = Student.builder().age(18).name("小三子").car(car).build();

         return student;

     }


    public static void main(String[] args) {

        // 通过静态工厂方法 Optional.empty(),创建一个空的 Optional 对象
//        Optional<Student> optStudent1 = Optional.empty();

        /*
        * 静态工厂方法 Optional.of(T t),依据一个非空值创建一个 Optional 对象
        * 等于null报空指针:java.lang.NullPointerException
        * */
//        Optional<Student> optStudent = Optional.of(getNullStudent());


        // 用静态工厂方法 Optional.ofNullable(T t),你可以创建一个允许 null 值的 Optional 对象
//        Optional<Student> optStudent = Optional.ofNullable(getNullStudent());
//        boolean present = optStudent.isPresent();
//        System.out.println(present);

        /*
        * 使用 isPresent() 方法检查 Optional 对象是否包含非空值
        * */
//        Optional<String> optional = Optional.of("Hello World");
//        if (optional.isPresent()) {
//            System.out.println(optional.get());
//        }

//        Optional.ofNullable(getNotNullStudentAge18()).ifPresent(System.out::println);
//
//        Optional.ofNullable(getNullStudent()).ifPresent(System.out::println);
//
//        Optional.ofNullable(getNotNullStudentAgeIsNull()).ifPresent(System.out::println);

        /*Optional<Student> notNullStudentAgeIsNull = Optional.ofNullable(getNotNullStudentAgeIsNull());
        notNullStudentAgeIsNull.ifPresent(o->o.setAge(19));*/

        /*
        map() 方法,如果值存在,就对该值执行提供的 mapping 函数调用,如果值不存在,则返回一个空的 Optional 对象。
        引入 Optional 以前:
        String name = null;
        if( insurance != null){
            name = insurance.getName();
        }
        引入 Optional 以后:
        */

//        Optional<String> s = Optional.ofNullable(getAllStudent()).map(Student::getName);
//        s.ifPresent(System.out::println);
//
//        String name = Optional.ofNullable(getAllStudent()).map(Student::getName).orElse(null);
//        System.out.println(name);


        /*Optional<String> name = Optional.ofNullable(getNullStudent()).map(Student::getName);//Optional.empty();
        String ss = name.orElse("不存在就附默认值");
        System.out.println(ss);*/


        /*
          flatMap() 方法,对于嵌套式的 Optiona 结构,我们应该使用 flatMap 方法,将两层的 Optional 合并成一个。
          重构如下代码:
            public String getCarInsuranceName(Person person) {
                return person.getCar().getInsurance().getName();
            }
         */

        /*Optional<Student> allStudent = Optional.ofNullable(getAllStudent());

        String unknown = allStudent.flatMap(Student::getOptionalCar)
                .flatMap(Car::getOptionalInsurance)
                .map(Insurance::getName)
                .orElse("Unknown");// 如果Optional的结果 值为空设置默认值
        System.out.println(unknown);*/

        //orElseGet(Supplier<? extends T> other) 方法,它是 orElse 方法的延迟调用版,Supplier 方法只有在 Optional 对象不含值时才执行调用(懒加载):
        /*Optional<Student> notNullStudentAgeIsNull = Optional.ofNullable(getNotNullStudentAgeIsNull());
        notNullStudentAgeIsNull.map(Student::getAge).orElse(Integer.MAX_VALUE);
        notNullStudentAgeIsNull.map(Student::getAge).orElseGet(() -> Integer.MAX_VALUE);*/

        /*Optional<Student> notNullStudentAgeIsNull = Optional.ofNullable(getNullStudent());//orElseThrow(Supplier<? extends X> exceptionSupplier) 方法,它和 get 方法非常类似,它们遭遇 Optional 对象为空时都会抛出一个异常,但是使用 orElseThrow 可以定制希望抛出的异常类型:

        notNullStudentAgeIsNull.orElseThrow(() -> new RuntimeException("student不存在!"));*/


        /*filter() 方法接受一个谓词作为参数。如果 Optional 对象的值存在,并且它符合谓词的条件,filter 方法就返回其值,否则它就返回一个空的 Optional 对象。
        * 比如,你可能需要检查保险公司的名称是否为 “Cambridge-Insurance”。
        *     Insurance insurance = ...;
            if(insurance != null && "CambridgeInsurance".equals(insurance.getName())){
                    System.out.println("ok");
          }
        *使用 Optional 对象的 filter 方法,这段代码可以重构如下:
        * */
        Optional<Student> optionalStudent = Optional.ofNullable(getAllStudent());

        Optional<Student> optionalStudent1 = optionalStudent.filter(student -> "小三子".equals(student.getName()));

        optionalStudent.filter(student -> "小三子".equals(student.getName()))
                .ifPresent(x -> System.out.println("ok"));


    }
}

 

posted @ 2024-06-28 09:53  慎终若始  阅读(5)  评论(0编辑  收藏  举报