打赏
Fork me on GitHub

Java8 新特性 - Optional

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

测试代码如下:

package com.xq.java8;

import com.xq.design.model.Employee;
import org.junit.jupiter.api.Test;
import java.util.Optional;

public class TestOptional {
    @Test
    public void test1(){
        Optional<Employee> op = Optional.of(new Employee());
        Employee  emp =op.get();
        System.out.println(emp);
    }
    @Test
    public void test2(){
        Optional<Employee> op =Optional.empty();
        System.out.println(op.get());
    }
    @Test
    public void test3(){
        Optional<Employee> op = Optional.ofNullable(null);
        if(op.isPresent()){
            System.out.println(op.get());
        }
        Employee emp  = op.orElse(new Employee("张三",18,888.88, Employee.Status.FREE));
        System.out.println(emp);

        Employee emp1 = op.orElseGet(() -> new Employee());
        System.out.println(emp1);

        Optional<Employee> op1 = Optional.ofNullable(new Employee());
        if(op1.isPresent()){
            System.out.println(op1.get());
        }
    }

    @Test
    public void test4(){
        Optional<Employee> op = Optional.ofNullable(new Employee("张三",18,888.88, Employee.Status.FREE));
        Optional<String> name = op.map((e) -> e.getName());
        System.out.println(name.get());

        Optional<String> ops = op.flatMap((e) -> Optional.of(e.getName()));
        System.out.println(ops.get());
    }
}

 

posted @ 2020-02-16 17:31  l-coil  阅读(118)  评论(0编辑  收藏  举报