What is the Optional.ifPresent method in Java?

In Java, the Optional object is a container object which may or may not contain a value.

The Optional class is present in the java.util package. Using the Optional object’s isPresent method, we can replace the multiple null check.

Read more about the Optional class here.

What is the ifPresent method of the Optional class?

The ifPresent method executes the given function if the value is present in the Optional object.

public void ifPresent​(Consumer<? super T> action)

Argument

This method takes the function to be executed as an argument. The function will be executed only if the Optional object contains a value.

Return value

This method does not return any value.

Code

The below code denotes how to use the ifPresent method.

import java.util.Optional;
class OptionalIfPresentExample {
public static void main(String[] args) {
Optional<Integer> optional1 = Optional.of(1);
optional1.ifPresent((value)->{
System.out.println("Value at Optional1 is : " + value);
});
Optional<Integer> optional2 = Optional.empty();
optional2.ifPresent((value)->{
System.out.println("Value at Optional2 is : " + value);
});
}
}

Explanation

In the above code:

  • In line 1, we import the Optional class.
import java.util.Optional;
  • In line 5, we create an Optional object of the Integer type with value 1, using the of method.
Optional<Integer> optional1 = Optional.of(1);
  • In line 6, we call the ifPresent method on the optional1 object with a function as an argument. This function is executed and prints the value of the optional1 object.
optional1.ifPresent((value)->{
    System.out.println("Value at Optional1 is : " + value);
});

// Optional1 is. : 1 
  • In line 10, we use the empty method to get an empty Optional object of the Integer type. The returned object does not have any value.
Optional<Integer> optional2 = Optional.empty();
  • In line number 11, we call the ifPresent method on the optional2 object with a function as an argument. This function does not get executed because the optional2 object does not have any value.
optional2.ifPresent((value)->{
    System.out.println("Value at Optional1 is : " + value);
});
// the function passed as an argument will not get executed

Free Resources