Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 Optional - how to handle nested Object structures

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;
    }
}
}
like image 872
Valath Avatar asked May 05 '18 06:05

Valath


People also ask

What exception is thrown by optional get () when not nested within optional isPresent ()?

Simply put, if the value is present, then isPresent() would return true, and calling get() will return this value. Otherwise, it throws NoSuchElementException.

How do you handle optional null values?

Optional from nullable value: You can create an optional object from a nullable value using the static factoy method Optional. ofNullable . The advantage over using this method is if the given value is null then it returns an empty optional and rest of the operations performed on it will be supressed.

What is isPresent in optional?

The isPresent() method of java. util. Optional class in Java is used to find out if there is a value present in this Optional instance. If there is no value present in this Optional instance, then this method returns false, else true.


1 Answers

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);
like image 78
user7 Avatar answered Oct 01 '22 01:10

user7