use Optional in java 8



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


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 :