1.Optional容器类
Optional<T> 类(java.util.Optional) 是一个容器类,代表一个值存在或不存在,原来用 null 表示一个值不存在,现在 Optional 可以更好的表达这个概念。并且可以避免空指针异常。
常用方法 :
- Optional.of(T t) : 创建一个 Optional 实例
- Optional.empty() : 创建一个空的 Optional 实例
- Optional.ofNullable(T t) : 若 t 不为 null,创建 Optional 实例;否则创建空实例
- isPresent() : 判断是否包含值
- orElse(T t) : 如果调用对象包含值,返回该值,否则返回t
- orElseGet(Supplier s) : 如果调用对象包含值,返回该值,否则返回 s 获取的值
- map(Function f) : 如果有值对其处理,并返回处理后的Optional,否则返回 Optional.empty()
- flatMap(Function mapper) : 与 map 类似,要求返回值必须是Optional
2.应用举例
下面的代码案例按照上面所列方法顺序给出。首先需要一个Employee类用作测试。
package com.szh.java8;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Employee {
private Integer id;
private String name;
private Integer age;
private Double salary;
}
@Test
public void test1() {
Optional<Employee> op = Optional.of(new Employee());
Employee employee = op.get();
System.out.println(employee);
}
@Test
public void test2() {
Optional<Employee> op = Optional.empty();
System.out.println(op.get());
}
@Test
public void test3() {
Optional<Employee> op = Optional.ofNullable(new Employee(1001,"张起灵",18,6666.66));
System.out.println(op.get());
}
@Test
public void test4() {
Optional<Employee> op = Optional.of(new Employee());
if (op.isPresent()) {
System.out.println(op.get());
}
}
@Test
public void test5() {
Optional<Employee> op1 = Optional.ofNullable(null);
Employee employee1 = op1.orElse(new Employee(1001,"张起灵",18,6666.66));
System.out.println(employee1);
Optional<Employee> op2 = Optional.ofNullable(new Employee());
Employee employee2 = op2.orElse(new Employee(1001,"张起灵",18,6666.66));
System.out.println(employee2);
}
@Test
public void test6() {
Optional<Employee> op1 = Optional.ofNullable(null);
Employee employee1 = op1.orElseGet(() -> new Employee(1001,"张起灵",18,6666.66));
System.out.println(employee1);
Optional<Employee> op2 = Optional.ofNullable(new Employee());
Employee employee2 = op2.orElseGet(() -> new Employee(1001,"张起灵",18,6666.66));
System.out.println(employee2);
}
@Test
public void test7() {
Optional<Employee> op1 = Optional.of(new Employee(1001,"张起灵",18,6666.66));
Optional<String> op2 = op1.map(Employee::getName);
System.out.println(op2.get());
Optional<String> op3 = op1.flatMap((e) -> Optional.of(e.getName()));
System.out.println(op3.get());
}
以上就是深入理解Java8新特性之Optional容器类的应用的详细内容,更多关于Java Optional容器类的资料请关注编程网其它相关文章!