Home > Software engineering >  mapping function returns null, orElseGet is being called when i don't want it to be
mapping function returns null, orElseGet is being called when i don't want it to be

Time:12-08

Let's say I have the following function:

private void func(final String name, final String zipcode) {
    this.userService.findUser(userId).map(user -> {
        this.userService.update(user.getId(), zipcode);
        return null; // because a return is needed
    }).orElseGet(() ->  this.userService.create(name, zipcode));
}

I can't change update and findUser signatures (void and Optional being the relevant parts):

public void update(final UUID userId, String zipcode)

public Optional<User> findUser(final UUID userId)

I have to return something in the function being given to the map, but returning null will make orElseGet get called everytime.

Is the only way to use map correctly in this case (not calling orElseGet when a user is found) to return something else other than null?

If so, is there another good way to write this code?

Returning something random just to make it work doesn't feel correct.

CodePudding user response:

You can use Optional.ifPresentOrElse(). For example:

private void func(final String name, final String zipcode) {
this.userService.findUser(userId)    
    .ifPresentOrElse(user -> this.userService.update(user.getId(), zipcode),
    () -> this.userService.create(name, zipcode));
}
  •  Tags:  
  • java
  • Related