Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problem while converting old-school if usage to Optional.ifPresent()

I am facing a problem while converting old-school if usage to Optional.ifPresent. Here is the previous version of the code.

State state = State.OK;
final Optional<Person> checkExistingPerson = checkIt();

if(checkExistingPerson.isPresent()) {
    Person person = checkExistingPerson.get();

    if("blah".equals(person.getName())) {
        state = State.DUPLICATE;
    } else {
        state = State.RESTORED;
    }

    return Member(person.getId(), state);
}

return Member(null, state);

And here is the Optional.ifPresent usage

State state = State.OK;
final Optional<Person> checkExistingPerson = checkIt();

checkExistingPerson.ifPresent(person -> {

    if("blah".equals(person.getName())) {
        state = State.DUPLICATE;
    } else {
        state = State.NEW;
    }

    return Member(person.getId(), state);
});

return Member(null, state);

And also, here is the screenshot what IntelliJ forces me to change it. enter image description here

What is the best approach to use Optional regarding to my problem? Thx all!

like image 867
vtokmak Avatar asked Dec 31 '25 04:12

vtokmak


2 Answers

  1. External variables inside lambdas need to be final.
  2. ifPresent accepts a Consumer so it has no return value, therefore you can't use return Member(person.getId(), state); (also remember that you are inside a lambda, so return is not going to exit from your method, but from the lambda).

map instead accepts a Function which has a return value, so you could use it instead of ifPresent.

This is how you could refactor your code, by moving state inside the lambda and by using map and orElseGet:

return checkExistingPerson.map(person -> {
    State state;

    if("blah".equals(person.getName())) {
        state = State.DUPLICATE;
    } else {
        state = State.NEW;
    }

    return Member(person.getId(), state);
})
.orElseGet(() -> Member(null, State.OK));
like image 197
Loris Securo Avatar answered Jan 01 '26 16:01

Loris Securo


You can't change the value of a local variable from within a lambda expression. Besides, ifPresent can't return a value, as its return type is void.

Instead, you should use Optional.map, which transform the object wrapped by Optional if it's present:

return checkExistingPerson
    .map(person -> new Member(
            person.getId(), 
            "blah".equals(person.getName()) ? State.DUPLICATE : State.RESTORED))
    .orElse(new Member(null, State.OK));
like image 45
fps Avatar answered Jan 01 '26 18:01

fps



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!