use OptionalDouble in java 8



Program/ Example - use OptionalDouble - in java 8
import java.util.OptionalDouble;
/**
* Write a program to - use OptionalDouble - in java 8
*/
public class OptionalDoubleExample {
   public static void main(String[] args) {
       OptionalDouble optionalDouble = OptionalDouble.of(5.0);
       System.out.println("optionalDouble.isPresent() = "+optionalDouble.isPresent()); //isPresent() will return true - If a value is present
       //get() returns the value.
       System.out.println("optionalDouble.get() = "+optionalDouble.getAsDouble()); //5.0
      
       //orElse method - Return the value if present, otherwise return other.
       System.out.println("optionalDouble.orElse = "+optionalDouble.orElse(6.0)); //value is present, so it will print 5.0
      
       System.out.println("\n1 - optionalDouble.ifPresent");
       //ifPresent method - If a value is present, it invokes the specified consumer with the value, otherwise do nothing
       optionalDouble.ifPresent(System.out::println); //5.0 //It invokes  specified consumer i.e. System.out::println
       System.out.println("\n2 - optionalDouble.ifPresent");
          // Display some custom message if value is present
          optionalDouble.ifPresent((d) -> System.out.println("value = " + d)); // value = 5.0
         
   }
}
/* OUTPUT
optionalDouble.isPresent() = true
optionalDouble.get() = 5.0
optionalDouble.orElse = 5.0
1 - optionalDouble.ifPresent
5.0
2 - optionalDouble.ifPresent
value = 5.0
*/


Having any doubt? or you you liked the tutorial! Please comment in below section.
Please express your love by liking JavaMadeSoEasy.com (JMSE) on facebook, following on google+ or Twitter.







eEdit
Must read for you :