logo image

Java9 example for using ifPresentOrElse on OptionalInt Object



First create a OptionalInt object, you can do that with the following code

OptionalInt optionalIntWithValue = OptionalInt.empty(); // Without value
		
OptionalInt optionalIntWithOutValue = OptionalInt.of(10); // With value

Now you can use the ifPresentOrElse method an IntConsumer and a Runnable as shown below

optionalIntWithValue.ifPresentOrElse((value) -> {
	System.out.println("1. Value is present, its:" + value);
}, () -> {
	System.out.println("1. No Value present"); 
});

Complete Class

import java.util.OptionalInt;

public class OptionalIntExample {
	public static void main(String[] args) {

		OptionalInt optionalIntWithValue = OptionalInt.empty(); // Without value
		
		OptionalInt optionalIntWithOutValue = OptionalInt.of(10); // With value

		optionalIntWithValue.ifPresentOrElse((value) -> {
			System.out.println("1. Value is present, its:" + value);
		}, () -> {
			System.out.println("1. No Value present"); 
		});
		
		optionalIntWithOutValue.ifPresentOrElse((value) -> {
			System.out.println("2. Value is present, its:" + value);
		}, () -> {
			System.out.println("2. No Value present"); 
		});
	}
}

Output:

1. No Value present
2. Value is present, its:10