Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to use Optional.map()

Consider the below interfaces:

public interface Vc{
}

public interface Vd< P extends Vc, C extends Vcc<{
...
}

public interface VcResult extends Vc{
}

There exists a method which returns Optional

public Optional<Vc> getData()

Here is the method where I am trying to improve the code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

public VcResult mainMethod(){
  Optional<Vc> vc = getData();
  if(vc.isEmpty){
    return anotherMethod();  
  }
  return (VcResult)vc.get();
}

Please suggest in converting this portion:

if(vc.isEmpty){
      return anotherMethod();  
   }
   return (VcResult)vc.get();

to this:

vc.map()..orElseGet(() -> anotherMethod());

What will be the argument of map in the above statement.

>Solution :

You can use VcResult‘s class object to cast it:

public VcResult mainMethod(){
    return getData().map(VcResult.class::cast).orElseGet(this::anotherMethod);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading