How to use OptionalInt in java 8





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



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 :