Optional判空

jdk8新特性Optional

package com.zenqgifeng.practicedemo.jdk8newproperties;

import org.junit.Test;

import java.util.Optional;

/**
 * @author zengqifeng
 * @version 1.0
 * @date 2020/1/3 17:38
 * Optional  可以容纳null 的容器   orElse  ifPresent   ifPresentOrElse     map等方法避免对null的判断,写出更优雅的代码
 * Optional  判空步骤
 * 1、需要判定的对象存入容器
 * 2、容器操作       判断是否为null,默认值处理    map等操作
 * 3、得出结论,并根据结论做处理
 */
public class Demo07 {

    @Test
    public void test1() {
        String name = "迪丽热巴";
        Optional<String> empty = Optional.empty();
        Optional<String> optionalName = Optional.of(name);
        Teacher teacher = new Teacher("zhansg", 20);
        //teacher = null;
        Optional<Teacher> teacher1 = Optional.of(teacher);
        //判断是否为空
        /*boolean present = optionalName.isPresent();
        System.out.println(present);*/
        //为空给出默认值
        /*name = empty.orElse("杨幂");
        System.out.println(name1);*/
        //存在就做什么
        /*optionalName.ifPresent(System.out::println);*/
        String s = teacher1.map(t -> {
            return t.getName();
        }).map(t -> {
            return t.toUpperCase();
        }).get();
        System.out.println(s);
    }
}

class Teacher {
    private String name;
    private Integer age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Teacher{" +
                "name='" + name + '\'' +
                ", age=" + age +
                '}';
    }

    public Teacher(String name, Integer age) {
        this.name = name;
        this.age = age;
    }
}

你可能感兴趣的:(JDK8新特性)