AnOldSoul
AnOldSoul

Reputation: 4207

Simplifying if, else-if, else with Java optional

I have a method which takes in 3 parameters, all of which are optional. Implementation of the method is as follows.

public static Person getPerson(Optional<String> id, Optional<List> jobs, Optional<String> country) {
    Person p = null;
 
    if(id.isPresent() && jobs.isPresent()) {
      p = Person.builder.withName("Name").withId(id.get()).withJobs(jobs.get()).build();
    } else if (id.isPresent()) {
       p = Person.builder.withName("Name").withId(id.get()).build();
    } else {
       p = Person.builder.withName("Name").build();
    }
    return p;
}

Is there a way to simplify this with Optional.map.orElseGet pattern? If its just the id I could think of a way, but since jobs is also optional I'm not sure how I could use that. Any advice to refactor this code would be much appreciated.

Upvotes: 2

Views: 743

Answers (1)

Thiyagu
Thiyagu

Reputation: 17890

Create a builder object and use ifPresent and assign the corresponding fields.

PersonBuilder builder = Person.builder.withName("Name");

id.ifPresent(idValue -> builder.withId(idValue));
jobs.ifPresent(jobsValue -> builder.withJobs(jobsValue));

return builder.build();

As Michael suggests, you can also replace the lambda expression with a method reference (builder::withId, builder::withJobs).

Upvotes: 4

Related Questions