Java 8 Optional - how to handle nested Object structures

Valath :

Is there any simple way to reduce the lines of code to print the innermost not null object using Optional as alternative to the below code. I feels like we have to write more lines of code to avoid the null checks now.

Is there any easy way to make this code short and sweet in Java 8?

import java.util.Optional;

public class OptionalInnerStruct {

public static void main(String[] args) {

    // creepy initialization step, dont worry
    Employee employee = new Employee();
    employee.setHuman(Optional.empty());

    // with optional
    Optional<Human> optionalHuman = employee.getHuman();
    if (optionalHuman.isPresent()) {
        Human human = optionalHuman.get();
        Optional<Male> optionalMale = human.getMale();
        if (optionalMale.isPresent()) {
            Male male = optionalMale.get();
            Optional<Integer> optionalAge = male.getAge();
            if (optionalAge.isPresent()) {
                System.out.println("I discovered the variable finally " + optionalAge.get());
            }

        }

    }

    // without optional in picture, it will be something like:
    /*if(null! = employee.getHuman() && null!= employee.getHuman().getMale() && null! = employee.getHuman().getMale().getAge()) {
        System.out.println("So easy to find variable " + employee.getHuman().getMale().getAge());
    }*/
}

static class Employee {

    Optional<Human> human;

    public Optional<Human> getHuman() {
        return human;
    }

    public void setHuman(Optional<Human> human) {
        this.human = human;
    }
}

class Human {
    Optional<Male> male;

    public Optional<Male> getMale() {
        return male;
    }

    public void setMale(Optional<Male> male) {
        this.male = male;
    }
}

class Male {
    Optional<Integer> age;

    public Optional<Integer> getAge() {
        return age;
    }

    public void setAge(Optional<Integer> age) {
        this.age = age;
    }
}
}
user7 :

You can use Optional.flatMap here

employee.getHuman()
        .flatMap(Human::getMale)
        .flatMap(Male::getAge)
        .ifPresent(age -> System.out.println("I discovered the variable finally " + age);

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=474104&siteId=1