Use Optional to judge null instead of cumbersome if ... else

Let's first look at the traditional method of judging null, where various if elses are stacked together:

     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);
                }
            }
        } 

Use Optional instead of 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);
        

If one of the steps is null, the result will directly return null, and no NPE will be reported.

Guess you like

Origin blog.csdn.net/Maxiao1204/article/details/129441784