Optional
Optional 类是一个可以为null的容器对象。如果值存在则isPresent()方法会返回true,调用get()方法会返回该对象。
Optional 是个容器:它可以保存类型T的值,或者仅仅保存null。Optional提供很多有用的方法,这样我们就不用显式进行空值检测。
Optional 类的引入很好的解决空指针异常
判断参数是否为空
ofNullable(可以传递一个空对象)
Of(不可以传递空对象)
Optional<Student> student = Optional.ofNullable(null);
Optional<Student> student1 = Optional.of(new Student("zhangsan", 8));
System.out.println(student.isPresent()+"|||"+student1.isPresent());
结果
false|||true
参数为空可以设定默认值
Integer a1 = 5;
// Optional<Integer> a = Optional.ofNullable(a1);
// System.out.println(a.get());
// System.out.println(a.isPresent());
Integer a = Optional.ofNullable(a1).orElse(10);
System.out.println(a);
参数实现过滤
Student student1 = new Student("xiaowei",5);
Student student2 = new Student("zhangsan",6);
Optional<Student> a = Optional.ofNullable(student1);
boolean isPresent = a.filter(a2 -> a2.getAge() < student2.getAge()).isPresent();
System.out.println(isPresent);
//true