亲宝软件园·资讯

展开

Java Optional容器类 深入理解Java8新特性之Optional容器类的应用

张起灵-小哥 人气:0
想了解深入理解Java8新特性之Optional容器类的应用的相关内容吗,张起灵-小哥在本文为您仔细讲解Java Optional容器类的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:Java,Optional容器类,Java8,新特性,下面大家一起来学习吧。

1.Optional容器类

Optional<T> 类(java.util.Optional) 是一个容器类,代表一个值存在或不存在,原来用 null 表示一个值不存在,现在 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());
    }

加载全部内容

相关教程
猜你喜欢
用户评论