使用 Optional 判 null 替代繁琐的 if ... else

先看下传统的判 null 的方法,各种 if else 堆叠在一起:

     Student student = new Student();
        if (student != null) {
            ClassRoom classRoom = student.getClassRoom();
            if (classRoom != null) {
                Seat seat = classRoom.getSeat();
                if (seat != null) {
                    Integer row = seat.getRow();
                    System.out.println(row);
                }
            }
        } 

使用Optional 替代 if ... else:

Student student = new Student();
        Integer row = Optional.ofNullable(student)
                .map(Student::getClassRoom)
                .map(ClassRoom::getSeat)
                .map(Seat::getRow)
                .orElse(null);
            System.out.println(row);
        

这其中如果有一步为null,那么结果将直接返回null,不会报NPE的问题

猜你喜欢

转载自blog.csdn.net/Maxiao1204/article/details/129441784