When I need to use Optional.orElseGet() over Optional.orElse()

Viewed 25385

I need a clear explanation of this, even though I read this link on differences but no clear clarity. So can anyone explain to me on this in short with code?

3 Answers

As answered here, you might want to consider the second approach when the required resource is expensive to get.

// Always get heavy resource
getResource(resourceId).orElse(getHeavyResource()); 

// Get heavy resource when required.
getResource(resourceId).orElseGet(() -> getHeavyResource()) 
Related