实体类
package po;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Student implements Serializable {
private String name;
private Address address;
}
package po;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@AllArgsConstructor
@Data
@NoArgsConstructor
public class Address {
private String city;
}
Optional对非空对象的处理
满足过滤条件返回的值
package com.demo;
import po.Address;
import po.Student;
import java.util.Optional;
public class TestCase3 {
public static void main(String[] args) {
Student student = new Student("张三", new Address("香港"));
Student student1 = Optional.ofNullable(student)
.filter(s -> "张三1".equals(s.getName()))
.orElseGet(() -> new Student("李四", new Address("北京")));
System.out.println(student1);
}
}
![在这里插入图片描述](https://img-blog.csdnimg.cn/direct/8d8e46cbb22d4e4c84e2370264589e4d.png)
不满足条件返回的值
package com.demo;
import po.Address;
import po.Student;
import java.util.Optional;
public class TestCase3 {
public static void main(String[] args) {
Student student = new Student("张三", new Address("香港"));
Student student1 = Optional.ofNullable(student)
.filter(s -> "张三".equals(s.getName()))
.orElseGet(() -> new Student("李四", new Address("北京")));
System.out.println(student1);
}
}
![在这里插入图片描述](https://img-blog.csdnimg.cn/direct/9bf936960f1e482d8476158e2a0cbce3.png)