简体   繁体   中英

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.

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 ).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM