Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a method with parameters from an optional object in java

Let's consider the following class

class A{
    void met(int i){
       //do somthing
    }
}

and let's consider that we have an optional object of this class like:

Optional<A> a;

is it possible to call the method met on the object a without the need to check whether a refers to a full object or just empty (null). Something like:

a.map(A::met(5));

Unfortunately this code doesn't compile. How can this be done?

like image 533
Anas Avatar asked Dec 17 '14 09:12

Anas


1 Answers

There are two reasons why this can't work:

a.map(A::met(5));
  1. met returns nothing, and map must map the input Optional to an output Optional.
  2. method references don't take arguments, so you should use a lambda expression.

What you need is :

a.ifPresent(x->x.met(5));

Another option :

a.orElse(new A()).met(5);

This will execute met(5) on a dummy instance if a is empty, so it's probably not the best way.

like image 152
Eran Avatar answered Oct 09 '22 14:10

Eran