1.构建Optional
Optional<People> optionalInstance = Optional.of(new People()); //根据非空值创建一个Optional
Optional<People> optionalOrNull = Optional.ofNullable(p);//允许null值的Optional
Optional<Object> optionalEmpty = Optional.empty(); //声明一个空的Optional
2.常用API
optionalInstance.get(); //变量存在返回值否则抛出异常
optionalInstance.orElse(); //变量存在返回值否则返回默认值
optionalInstance.orElseGet(); //Optional为空时才进行调用传入的函数
optionalInstance.ifPresent(); //变量存在时执行一个作为参数传入的方法,否则不进行任何操作
optionalInstance.orElseThrow(); //变量为null时抛出异常
optionalInstance.filter(); //过滤
optionalInstance.map(); //变量值存在时调用转换
optionalInstance.ifPresent(); //值存在返回true,不存在返回false
3.代码demo
Person person = Person.builder().name("zs").age(12).build();
Optional.ofNullable(person).filter(p -> p.getAge() > 10).orElseThrow(() -> new Exception("hello, Optional"));
//从Optional对象中提取属性使用map
Optional<String> stringOptional = Optional.of(new Insurance()).map(Insurance::getName);
//多层Optional对象中提取使用flatmap
optionalPerson.flatMap(Person::getCar).flatMap(Car::getInsurance).map(Insurance::getName);