Getting started with Java 8 – Part 4

Click here to read about Getting started with Java 8- Part 3

Optional :-

   Optional is a highly underrated feature, and one that has the potential to remove a lot of those NullPointerExceptions that can plague us.

   It’s particularly useful at the boundaries of code (either APIs you’re using or APIs you’re exposing) as it allows you and your calling code to reason about what to expect.

   The strength of Optional is to express that the value might be empty and allow you to cater for that case.

   pubic Optional getConfig(){

       //implementation

   }

   Since the above method returns null the calling function would know that the value might be absent and will handle accordingly.

   public void method2 (String defaultValue){

     String config;

     Config configOptional = getConfig();

     if (ConfigOptional.isPresent){

       config = configOptional.getValue();

     }

     else {

       config = defaultValue

     }

     //implementation

   }

   Optional also contains map and filter that can be used to simplify the code. The above code can be simplified as below.

   public void method2 (String defaultValue){

     String config = getConfig()

       .map(Config::getValue)

       .orElse(defaultValue);



     //implementation

   }

   Java8 let us write simpler code, in the sense that they describe operations on data by saying what transformation is made rather than how the transformation occurs.

   This gives us code that has less potential for bugs and expresses the programmer’s intent directly.

   Happy Coding!

  Reference :-

  Java 8 Lambdas – by Richard Warburton

By:
Aditya Agrawal
www.coviam.com

Leave a Reply

Your email address will not be published.