Java 8 Optional的使用

简介

Optional是Java引入的类,用来解决空指针问题。并可以增加代码的整洁性。先看看源码介绍:

A container object which may or may not contain a non-null value. If a value is present, isPresent() returns true and get() returns the value.
Additional methods that depend on the presence or absence of a contained value are provided, such as orElse() (returns a default value if no value is present) and ifPresent() (performs an action if a value is present).

This is a value-based class; use of identity-sensitive operations (including reference equality (==), identity hash code, or synchronization) on instances of Optional may have unpredictable results and should be avoided.

简单来说:一个包含了null或非null对象的容器,若对象存在,则调用 isPresent() 返回true,调用get()返回当前对象。还提供了一些额外的方法来对包含的对象的处理。后续会介绍。另外就是这个是基于对象的类,避免使用对象敏感的操作,如equal或hash code等。

使用

Method Summary

(从源码中复制,仅供参考学习)

Modifier and TypeMethodDescription
static Optionalempty()Returns an empty Optional instance.
booleanequals(Object obj)Indicates whether some other object is “equal to” this Optional.
Optionalfilter(Predicate predicate)If a value is present, and the value matches the given predicate, returns an Optional describing the value, otherwise returns an empty Optional.
OptionalflatMap(Function> mapper)If a value is present, returns the result of applying the given Optional-bearing mapping function to the value, otherwise returns an empty Optional.
Tget()If a value is present, returns the value, otherwise throws NoSuchElementException.
inthashCode()Returns the hash code of the value, if present, otherwise 0 (zero) if no value is present.
voidifPresent(Consumer action)If a value is present, performs the given action with the value, otherwise does nothing.
voidifPresentOrElse(Consumer action,Runnable emptyAction)If a value is present, performs the given action with the value, otherwise performs the given empty-based action.
booleanisPresent()If a value is present, returns true, otherwise false.
Optionalmap(Function mapper)If a value is present, returns an Optional describing (as if by ofNullable(T)) the result of applying the given mapping function to the value, otherwise returns an empty Optional.
static Optionalof(T value)Returns an Optional describing the given non-null value.
static OptionalofNullable(T value)Returns an Optional describing the given value, if non-null, otherwise returns an empty Optional.
Optionalor(Supplier> supplier)If a value is present, returns an Optional describing the value, otherwise returns an Optional produced by the supplying function.
TorElse(T other)If a value is present, returns the value, otherwise returns other.
TorElseGet(Supplier supplier)If a value is present, returns the value, otherwise returns the result produced by the supplying function.
TorElseThrow(Supplier exceptionSupplier)If a value is present, returns the value, otherwise throws an exception produced by the exception supplying function.
Streamstream()If a value is present, returns a sequential Stream containing only that value, otherwise returns an empty Stream.
StringtoString()Returns a non-empty string representation of this Optional suitable for debugging.

使用

ofNullable, orElse
        Integer integer1 = 1;
        Integer integer2 = null;

        Optional<Integer> optional1 = Optional.ofNullable(integer1);
        Optional<Integer> optional2 = Optional.ofNullable(integer2);
        Integer test = optional2.orElse(3);
        
        System.out.println("optional1.get() = " + optional1.get());
        System.out.println("optional2.get() = " + test);

        //result:
        //optional1.get() = 1
        //optional2.get() = 3

基础使用如上方源码,可对对象做一个基本判空处理,若果为空,可赋予一个默认值;不为空,则返回当前值。

        ArrayList<Integer> arrayList = new ArrayList<>();
        optional1.ifPresent(arrayList::add);
        System.out.println("arrayList.get(0) = " + arrayList.get(1));

判空后会可以对数据处理操作,此处是若integer不为空的话,arrayList将其add进去,arrayList::add是lambda表达式,也是Java 8引入的,感兴趣的可以学习一下。

filter
        Optional<Integer> optional3 = optional1.filter(val -> val > 2);
        Optional<Integer> optional4 = optional1.filter(val -> val < 2);
        System.out.println("optional3.get() = " + optional3);
        System.out.println("optional4.get() = " + optional4.get());

        //result 
        //optional3.get() = Optional.empty
        //optional4.get() = 1

filter的方式用来做数据筛选,optional1包含的值是1,所以optional3.get()就会返回empty。

map, flatMap
            class Student {
        String userName;

        public String getUserName() {
            return userName;
        }

        public void setUserName(String userName) {
            this.userName = userName;
        }
    }

    class Teacher {
        String userName;

        public Optional<String> getUserName() {
            return Optional.ofNullable(userName);
        }

        public void setUserName(String userName) {
            this.userName = userName;
        }
    }

    class School {
        Student student;

        Teacher teacher;

        public Student getStudent() {
            return student;
        }

        public void setStudent(Student student) {
            this.student = student;
        }

        public Teacher getTeacher() {
            return teacher;
        }

        public void setTeacher(Teacher teacher) {
            this.teacher = teacher;
        }
    }
        
        
        Student student = new Student();
        student.setUserName("student");
        Teacher teacher = new Teacher();
        teacher.setUserName("teacher");
        School school = new School();
        school.setStudent(student);
        school.setTeacher(teacher);
        Optional<School> optional5 = Optional.ofNullable(school);

        String doubleName = optional5.map(School::getStudent).map(Student::getUserName).orElse("defalut");
        String teacherName = Optional.of(teacher).flatMap(Teacher::getUserName).orElse("teacher");
        System.out.println("doubleName = " + doubleName);
        System.out.println("teacherName = " + teacherName);

创建了三个对象,School,Teacher,Student,optional5.map(School::getStudent).map(Student::getUserName).orElse("defalut");

看到这行代码,就能知道,以后不用担心空指针,而不断的判断null了,直接一层一层使用map,进行数据返回。那么flatMap和map有什么区别呢,看代码好像是一样的,区别在于map封装了optional的返回,而flatMap没有,看一下teacher.getUserName()就可以看到:flatMap返回必须是optional,而map不用

public Optional<String> getUserName() {
            return Optional.ofNullable(userName);
        }

总结

Optional极大的减少了空指针的问题,并且简洁了代码,不用多层if,一直判断。好东西,请多用!

Java 8引入了Optional类,它是一个容器对象,可以包含或者不包含非空值。Optional类主要用于解决空指针异常的问题,它提供了一种优雅的方式来处理可能为空的值。 下面是Java 8 Optional使用方式: 1. 创建Optional对象: - 使用静态方法`Optional.of(value)`创建一个包含非空值的Optional对象。 - 使用静态方法`Optional.empty()`创建一个空的Optional对象。 - 使用静态方法`Optional.ofNullable(value)`创建一个包含可能为空值的Optional对象。 2. 判断Optional对象是否包含值: - 使用`isPresent()`方法判断Optional对象是否包含非空值。 - 使用`isEmpty()`方法判断Optional对象是否为空。 3. 获取Optional对象的值: - 使用`get()`方法获取Optional对象中的值。注意:如果Optional对象为空,调用`get()`方法会抛出NoSuchElementException异常。 4. 处理Optional对象的值: - 使用`ifPresent(Consumer<? super T> consumer)`方法,传入一个Consumer函数式接口来处理Optional对象中的值。如果Optional对象非空,则执行传入的Consumer接口中的逻辑。 - 使用`orElse(T other)`方法,如果Optional对象为空,则返回传入的默认值other。 - 使用`orElseGet(Supplier<? extends T> other)`方法,如果Optional对象为空,则通过传入的Supplier函数式接口生成一个默认值。 - 使用`orElseThrow(Supplier<? extends X> exceptionSupplier)`方法,如果Optional对象为空,则通过传入的Supplier函数式接口抛出一个异常。 5. 使用Optional进行链式调用: - 使用`map(Function<? super T, ? extends U> mapper)`方法,传入一个Function函数式接口来对Optional对象中的值进行转换。 - 使用`flatMap(Function<? super T, Optional<U>> mapper)`方法,传入一个Function函数式接口来对Optional对象中的值进行转换,并返回一个新的Optional对象。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值