1、isPresent
使用isPresent方法来判断非空,isPresent相当于!=null
isPresent 返回一个boolean
Optional<Student> optional = Optional.ofNullable(new Student("王五", 80));
if (optional.isPresent()){
// 将输出:student1不为空的操作
System.out.println("student不为空");
} else {
System.out.println("student is 空");
}
2、ifPresent
ifPresent 相当于相判断 !=null,不为空才执行里面的代码:
Optional<Student> optional = Optional.ofNullable(new Student("王五", 80));
optional.ifPresent(student -> System.out.println("学生姓名:"+ student.getName()));
3、获取数据
- get 如果为空会抛出NoSuchElementException异常,使用前 isPresent
- orElse 接受T类型的参数
- orElseGet 接收Supplier类型的参数
// optional不为空则返回student1给 student3,否则返回student2给student3
Student student1 = new Student("王五", 80);
Student student2 = new Student("张三", 90);
Optional<Student> optional = Optional.ofNullable(student1);
Student student3 = optional.orElseGet(()->student2)
4、map
map将谓词作为参数并返回一个Optional对象
List<String> companyNames = Arrays.asList("paypal", "oracle", "", "microsoft", "", "apple");
Optional<List<String>> listOptional = Optional.of(companyNames);
//获取companyNames的长度
int size = listOptional.map(List::size).orElse(0);
System.out.println(size);//6
获取学生名称大写
Student student1 = new Student("aaa", 80);
String stName = Optional.ofNullable(student1).map(s -> s.getName().toUpperCase()).orElse(null);
5、filter
filter 将谓词作为参数并返回一个Optional对象
Integer year = 2022;
boolean is2022 = Optional.ofNullable(year).filter(y -> y == 2022).isPresent();
System.out.println(is2022);//true
双重判断
判断价格是否在在10到15
Optional.ofNullable(modem)
.map(Modem::getPrice)
.filter(p -> p >= 10)
.filter(p -> p <= 15)
.isPresent();
标签:教程,isPresent,Optional,student1,ofNullable,Student,optional
From: https://www.cnblogs.com/cherychina/p/17493719.html