Modify the Optional<Person> if present

Viewed 218

I have a scenario where I am getting an Optional<Person> person from the DB and I need to modify the person as person.setRole("Admin") if the person is present and set it in my MainClass.java.

I tried :

var p = person.map(person1 -> person1.setRole("Admin"));

but this seems incorrect. I want to update the same object and not create a new one.

EDIT:

After setting the value I need to set this person object as it is member variable in Department class.

@Builder //lombok
class Department {
    private Long depId;
    private Person person;
}

MainClass.java

Department.builder()
          .depId(1L)
          .person( The person that I will get from the operation I need )
          .build()

Thanks in advance.

1 Answers

You haven't specified what you want to do if the Optional is empty. Since there are no @Builder.Default on top of person, I assume that you want to keep it as null when the optional is empty.

You could provide the ifPresent first to set the role. It would be executed only if value is present, otherwise does nothing. Then pass the object by invoking orElse on this object to the builder.

optPersonFromDb.ifPresent(p -> p.setRole("Admin"));
Department.builder()
          .depId(1L)
          .person(optPersonFromDb.orElse(null))
          .build();
Related