9

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;
    }
}
}
Neuron
  • 5,141
  • 5
  • 38
  • 59
Valath
  • 880
  • 3
  • 13
  • 35

1 Answers1

15

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);
Thiyagu
  • 17,362
  • 5
  • 42
  • 79
  • While using map API, we need to add an extra call to retrieve the value before using the transformed value. This way, the Optional wrapper will be removed. This operation is performed implicitly when using flatMap, from http://www.baeldung.com/java-optional , will be helpful for someone like me in future. – Valath May 05 '18 at 09:53