A RetroSearch Logo

Home - News ( United States | United Kingdom | Italy | Germany ) - Football scores

Search Query:

Showing content from https://www.geeksforgeeks.org/java/optional-orelseget-method-in-java-with-examples/ below:

Optional orElseGet() Method in Java

Optional orElseGet() Method in Java

Last Updated : 12 Jul, 2025

The orElseGet() method of java.util.Optional class in Java is used to get the value of this Optional instance if present. If there is no value present in this Optional instance, then this method returns the value generated from the specified supplier.

Syntax of orElseGet() Method

public T orElseGet(Supplier<? extends T> supplier)

Example 1: Using the orElseGet() method with optional chaining.

Java
// Java program to demonstrate 
// Optional.orElseGet() method 
import java.util.*; 
import java.util.function.*; 

public class Geeks
{ 

	public static void main(String[] args) 
	{ 

		// create a Optional 
		Optional<Integer> op 
			= Optional.of(9455); 

		// print supplier 
		System.out.println("Optional: "
						+ op); 

		// orElseGet supplier 
		System.out.println("Value by orElseGet"
						+ "(Supplier) method: "
						+ op.orElseGet( 
								() -> (int)(Math.random() * 10))); 
	} 
} 

a


Output
Optional: Optional[9455]
Value by orElseGet(Supplier) method: 9455

Explanation: In the above code, we use the Optional and assign the value as 9455 and the supplier is not called. If the supplier generates the random value when optional is empty.

Example 2: Using orElseGet() method with an empty optional.

Java
// Java program to demonstrate 
// Optional.orElseGet() method 
import java.util.*; 
import java.util.function.*; 

public class Geeks
{ 

	public static void main(String[] args) 
	{ 
		// create a Optional 
		Optional<Integer> op 
			= Optional.empty(); 

		// print supplier 
		System.out.println("Optional: "
						+ op); 

		try { 

			// orElseGet supplier 
			System.out.println("Value by orElseGet"
							+ "(Supplier) method: "
							+ op.orElseGet( 
									() -> (int)(Math.random() * 10))); 
		} 
		catch (Exception e) { 
			System.out.println(e); 
		} 
	} 
} 

Output
Optional: Optional.empty
Value by orElseGet(Supplier) method: 6

Explanation: In the above code, the optional is empty so when the method calls the supplier generate the the random value because in the supplier we define the Math.random().



RetroSearch is an open source project built by @garambo | Open a GitHub Issue

Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo

HTML: 3.2 | Encoding: UTF-8 | Version: 0.7.4