Optional orElseGet Method

🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.

▶️ Subscribe to My YouTube Channel (178K+ subscribers): Java Guides on YouTube

▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube

In this tutorial, we will demonstrate how to get the default value using the Optional orElseGet() method.

The orElseGet() method returns the value if present, otherwise returns the result of that invocation.

Java Optional orElseGet() Method Example

In the below example, orElseGet() method returns the default value because Optional contains a null value:

import java.util.Optional;

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

        String email = null;
        Optional<String> stringOptional = Optional.ofNullable(email);
        String defaultOptional2 = stringOptional.orElseGet(() -> "default@gmail.com");
        System.out.println(defaultOptional2);
    }
}
Output:
default@gmail.com
In the below example, the orElseGet() method returns the actual value because Optional contains an actual value:
import java.util.Optional;

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

        String email = "ramesh@gmail.com";
        Optional<String> stringOptional = Optional.ofNullable(email);
        String defaultOptional2 = stringOptional.orElseGet(() -> "default@gmail.com");
        System.out.println(defaultOptional2);
    }
}
Output:
ramesh@gmail.com

My Top and Bestseller Udemy Courses. The sale is going on with a 70 - 80% discount. The discount coupon has been added to each course below:

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare