什么是Optional

Optional是JDK8的一个新特性,用来判断一个对象是否为null

image.png

常用方法

public  flatMap(java.util.function.Function)
public Object orElse(Object)
public static  ofNullable(Object)
public void ifPresent(java.util.function.Consumer)
public boolean isPresent()
public Object orElseGet(java.util.function.Supplier)
public Object orElseThrow(java.util.function.Supplier) throws Throwable
public Object get()
public boolean equals(Object)
public static  of(Object)
public static  empty()
public  filter(java.util.function.Predicate)
public  map(java.util.function.Function)

初始化

  • Optional.of() 不允许为空
  • Optional.ofNullable() 允许为空
  • Optional.empty() 空的Optional
  • get() 访问被包装的元素
    @Test
    // 初始化测试
    public void initTest(){
        String name = "luckyFang";

        // 不允许为空 如果为空则抛出异常

        Optional<String> opt1 = null;
        try {
            opt1 = Optional.of(null);
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 允许为空
        Optional<String> opt2 = Optional.ofNullable(name);

//        System.out.println(opt1.get());
        System.out.println(opt2.get());
        Optional<String> empty = Optional.empty();
        System.out.println(empty);

    }

isPresent

  • isPresent 是否存在
  • 如果:包装类为 null 则 为 false
  • 如果:包装类不为null 则为 true
    @Test
    public void isPresentTest() {
        String name = "luckyFang";
        boolean present = Optional.ofNullable(name).isPresent();
        System.out.println(present);

        boolean present2 = Optional.ofNullable(null).isPresent();
        System.out.println(present2);
    }

true
false

ifPresent

如果存在则执行 Consumer 否则 什么也不做

    @Test
    public void ifPresent(){
        String name ="luckyFang";

        Optional<String> opt1 = Optional.ofNullable(name);
        opt1.ifPresent(new Consumer<String>() {
            @Override
            public void accept(String s) {
                System.out.println(s);
            }
        });

        // 方法引入改进
        opt1.ifPresent(System.out::println);

    }

luckyFang
luckyFang

filter

过滤器,通过断言实现

return:
- true 拦截
- false 放行

    @Test
    public void filterTest(){
        String name = "luckyFang";
        Optional<String> opt1 = Optional.ofNullable(name);
        String s = opt1.filter(new Predicate<String>() {
            @Override
            public boolean test(String s) {
                return true;
            }
        }).get();
        System.out.println(s);

    }
luckyFang

Q.E.D.


全栈混子的菜鸡日常