2-5 JDK8之Optional类

2-5 JDK8之Optional类


本小节内容将包含一定的Lambda表达式可先跳过观看第三章
产生背景:
空指针异常是导致Java应用程序失败的最常见原因。以前,为了解决空指针异常,Optional实际上是个容器:它可以保存类型T的值,或者仅仅保存null。Optional提供很多有用的方法,这样我们就不用显式进行空值检测。

注意:Optional是为了避免传统空指针异常,而并非是返回null

一、三种构造方式

1)、返回一个值为空的Optional对象

public class Main {
    public static void main(String[] args) {
        Optional<Student> optional = Optional.empty();
    }
}

2)、返回一个值不为空的Optional对象如果传入参数为空,则抛出空指针异常

public class Main {
    public static void main(String[] args) {
        Student student = null;
        Optional<Student> optional = Optional.of(student);// 此时返回空指针异常
        System.out.println(optional.get());
    }
}

3)、返回一个值可以为空或不为空的Optional对象

public class Main {
    public static void main(String[] args) {
        Student student = null;
        Optional<Student> optional = Optional.ofNullable(student);// 此时没有问题
    }
}

二、几个常用方法

公用类 Student

public class Student {
    private int age;

    public Student() {}
    public Student(int age) {
        this.age = age;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
    @Override
    public String toString() {
        return "Student{" +
                "age=" + age +
                '}';
    }
}

1)、isPresent()

判断值是否不为空,空返回 false(尽量避免使用此方法)

public class Main {
    public static void main(String[] args) {
        Student student = null;
        Student student2 = new Student(10);
        Optional<Student> optional = Optional.ofNullable(student);// 生成值为空的Optional
        Optional<Student> optional2 = Optional.ofNullable(student2);// 生成值不为空的Optional
        // 输出二者是否值不为空
        System.out.println(optional.isPresent()+"----"+optional2.isPresent());
        // 结果	false----true
    }
}

2)、get()

获取值对象(尽量避免使用此方法)

public class Main {
    public static void main(String[] args) {
        Student student = null;
        Student student2 = new Student(10);
        Optional<Student> optional = Optional.ofNullable(student);// 生成值为空的Optional
        Optional<Student> optional2 = Optional.ofNullable(student2);// 生成值不为空的Optional

//        System.out.println(optional.get()); // 抛出java.util.NoSuchElementException 异常
        System.out.println(optional2.get());
    }
}

3)、void ifPresent(Consumer<? super T> consumer)

对Optional值对象进行操作

public class Main {
    public static void main(String[] args) {
        Student student = new Student(10);
        Optional<Student> optional = Optional.ofNullable(student);// 生成值不为空的Optional
        optional.ifPresent(s -> System.out.println(s.getAge()));
        // 结果打印 10
    }
}

4)、Optional map(Function<? super T, ? extends U> mapper);

map 方法是链式调用避免空指针的核心方法, 当实例包含值时, 对值执行传入的 Function 逻辑, 并返回一个代表结果值的新的 Optional 实例. 这也意味着返回的结果依旧可以继续调用 map 方法, 而不需要空指针判断.

public class Main {
    public static void main(String[] args) {
        Student student = new Student(10);
        Optional<Student> optional = Optional.ofNullable(student);// 生成值不为空的Optional
        System.out.println(optional.map(s -> s.getAge()).map(o -> {
            System.out.println(o); //打印 10
            return ++o;
        }));
        // 结果打印 Optional[11]
    }
}

5)、T orElse(T other);

给Optional对象一个默认值,当值为空时返回这个对象

public class Main {
    public static void main(String[] args) {
        Student student = null;
        Optional<Student> optional = 
                Optional.of(Optional.ofNullable(student).orElse(new Student(10)));
        optional.ifPresent(s -> System.out.println(s.getAge()));
        // 结果打印 10
    }
}

未经授权不得转载或转载请注明出处

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值