@Data
public class Employee {
private String name;
}
@Data
public class Company {
private String name;
private List<Employee> employees;
}
/**
* optional接口, optional的使用都是基于函数式的用法, 不写if-else判断
* optional 无法序列化, 不要将她作为方法参数 或 类的成员变量, 只用在方法的返回值上,
* 用来规避空指针异常
*/
public class OptionalTest {
@Test
public void test() {
Optional<String> optional = Optional.of("hello");
// 无用的使用方式
if (optional.isPresent()) {
System.out.println(optional.get());
}
// 推荐的使用方式
optional.ifPresent(item -> System.out.println(item));
}
@Test
public void test2() {
Optional<String> optional = Optional.empty();
// 推荐的使用方式, 没有值将不执行传入的方法
optional.ifPresent(item -> System.out.println(item));
System.out.println("---------------------------------");
System.out.println(optional.orElse("world"));
System.out.println("---------------------------------");
System.out.println(optional.orElseGet(() -> "nihao"));
System.out.println("---------------------------------");
}
@Test
public void Test3() {
Employee employee = new Employee();
employee.setName("zhangsan");
Employee employee2 = new Employee();
employee2.setName("lisi");
Company company = new Company();
company.setName("company");
List<Employee> employees = Arrays.asList(employee, employee2);
company.setEmployees(employees);
List<Employee> list = company.getEmployees();
// 传统手工艺做法:
/*
if (null != list) {
return list;
} else {
return new ArrayList<Employee>();
}
*/
// 崭新的函数式风格
Optional<Company> optional = Optional.ofNullable(company);
System.out.println(
optional.map(c -> c.getEmployees()).orElse(Collections.emptyList())
);
}
}