If you have a default value for your Desktop, you could try with Optional.orElse:

Desktop defaultDesktop = ...;

Desktop desktop = Optional.ofNullable(status)
    .map(Status::getDesktop)
    .orElse(defaultDesktop);

However, you don't have to necessarily work inside a lambda expression with Optional.ifPresent. You could perfectly use a method that receives a Desktop instance, which would act as the Consumer argument of Optional.ifPresent:

Desktop desktop = Optional.ofNullable(status)
    .map(Status::getDesktop)
    .ifPresent(this::workWithDesktop);

Then:

void workWithDesktop(Desktop desktop) {
    // do whatever you need to do with your desktop
}

If you need additional arguments (apart from the desktop itself), you could use a lambda expression that invokes the method instead:

String arg1 = "hello";
int arg2 = 10;

Desktop desktop = Optional.ofNullable(status)
    .map(Status::getDesktop)
    .ifPresent(desktop -> this.workWithDesktop(desktop, arg1, arg2));

And then:

void workWithDesktop(Desktop desktop, String arg1, int arg2) {
    // do whatever you need to do with your desktop, arg1 and arg2
}
Answer from fps on Stack Overflow
🌐
Hackajob
hackajob.com › talent › blog › using-the-optional-feature-in-java-8
Using the Optional Feature in Java 8
October 9, 2023 - However, if an empty ‘Optional’ is used with the ‘orElseThrow’ method, it throws the specified exception as demonstrated below: ... Here, a ‘RuntimeException’ is specified in the ‘orElseThrow’ method, with the code printing the following output: Exception in thread "main" java.lang.RuntimeException
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-8-optional-class
Java 8 Optional Class - GeeksforGeeks
May 16, 2026 - The print statements display an empty Optional and an Optional holding a value, showing how Optional safely represents both cases. Example 2: Using get(), hashCode() and isPresent() ... import java.util.Optional; class GFG { public static void main(String[] args) { String[] str = new String[5]; str[2] = "Geeks Classes are coming soon"; Optional<String> value = Optional.of(str[2]); System.out.println(value.get()); System.out.println(value.hashCode()); System.out.println(value.isPresent()); } }
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › util › Optional.html
Optional (Java Platform SE 8 )
April 21, 2026 - If a value is present the result must include its string representation in the result. Empty and present Optionals must be unambiguously differentiable. ... Java™ Platform Standard Ed.
🌐
Code Like A Girl
code.likeagirl.io › java-8-optional-class-cde70f787c35
Java 8 Optional Class. Introduction | by Daily Debug | Code Like A Girl
December 19, 2024 - Optional helps to set clear intent of the code, Instead of returning Null to indicate that the value is absent you can return Optional.empty() to indicate that no value is present · When I first started exploring functional programming concepts in Java, Optional was a gateway to those ideas.
🌐
Medium
medium.com › @AlexanderObregon › javas-optional-orelseget-method-explained-d65c97250a9e
Java’s Optional.orElseGet() Explained | Medium
September 27, 2024 - Even if the Optional is not empty, the expensive computation will still occur. orElseGet() avoids this issue by only computing the default value when absolutely necessary, making it the better choice in scenarios involving expensive operations. Understanding when to use each method can save both time and computational resources in your Java applications.
Find elsewhere
🌐
Reddit
reddit.com › r/java › deprecating: java.util.optional.get()?
r/java on Reddit: Deprecating: java.util.Optional.get()?
April 28, 2016 - A while back (and probably even now) Brian Goetz took to basically every StackOverflow post about Optional to remind people that they only intended it as a return type, and even then, only when returning nulls was going to cause a high incidence of errors. In other words, for the Java 8 fluent Streams API.
🌐
LinkedIn
linkedin.com › pulse › introduction-java-8-optional-aneshka-goyal
Introduction to Java 8 Optional
December 30, 2020 - It is to be used as a return type so as to avoid null checks on returned values.The idea is to wrap the returned value within an optional. Thus we have a container object which may or may not contain a null value.
🌐
GeeksforGeeks
geeksforgeeks.org › java › optional-get-method-in-java-with-examples
Optional get() method in Java with examples - GeeksforGeeks
July 12, 2025 - // Java program to demonstrate // Optional.get() method import java.util.*; public class GFG { public static void main(String[] args) { // create a Optional Optional<Integer> op = Optional.empty(); // print value System.out.println("Optional: " + op); try { // get the value System.out.println("Value of " + "this Optional: " + op.get()); } catch (Exception e) { System.out.println(e); } } }
🌐
Davidvlijmincx
davidvlijmincx.com › home › java › optionals in java
Optionals in Java
December 15, 2024 - This will create an Optional from the given value and allowed to be null. When the instance is null the optional will be empty. To get a value out the optional you can use the get() method like this:
🌐
Baeldung
baeldung.com › home › java › core java › guide to java optional
Guide To Java Optional | Baeldung
February 15, 2026 - In this article, we covered most of the important features of Java 8 Optional class. We briefly explored some reasons why we would choose to use Optional instead of explicit null checking and input validation. We also learned how to get the value of an Optional, or a default one if empty, with the get(), orElse() and orElseGet() methods (and saw the important difference between the last two).
🌐
Stackify
stackify.com › optional-java
Understanding, Accepting and Leverage Optional in Java- Stackify
June 27, 2024 - Optional comes along with a strong move towards functional programming in Java and is meant to help in that paradigm, but definitely also outside of that. Let’s start with a simple use-case. Before Java 8, any number of operations involving accessing an object’s methods or properties could result in a NullPointerException: String isocode = user.getAddress().getCountry().getIsocode().toUpperCase();
🌐
Oracle
docs.oracle.com › en › java › javase › 11 › docs › api › java.base › java › util › Optional.html
Optional (Java SE 11 & JDK 11 )
January 20, 2026 - Optional is primarily intended for use as a method return type where there is a clear need to represent "no result," and where using null is likely to cause errors.
🌐
Medium
medium.com › @nweligalla › optional-in-java-8-5fbf12c90bfe
Optional in Java 8. Java Optional, introduced in Java 8… | by Nayana Weligalla | Medium
January 23, 2024 - Before Java Optional, developers had to manually check if a value was null to handle NullPointerExceptions in Java applications. Imagine you have a method called getText() that returns a string, and you want to print its uppercase version to the console in the main method.
🌐
Medium
medium.com › @dinukakasunmedis › exploring-java-optional-with-stream-api-2f091308113a
Exploring Java Optional with Stream API | by Dinuka Kasun Medis | Medium
October 8, 2024 - Java introduced the Optional class ... This is a container object that may or may not contain a value, offering a way to explicitly handle the absence of values rather than encountering null references....
🌐
Amydegregorio
amydegregorio.com › 2021 › 01 › 10 › java-basics-optional
Java Basics: Optional – Amy's Programming Corner
January 10, 2021 - There’s an important distinction between orElse and orElseGet that can effect performance in the case where the code executed for an empty Optional is more expensive. I could imagine a scenario where if the value wasn’t found we wrote a record to the database and returned that, for example. Let’s spruce up our example by calling a method to get a random Long if the Optional is empty.
Top answer
1 of 11
125

Style 2 isn't going Java 8 enough to see the full benefit. You don't want the if ... use at all. See Oracle's examples. Taking their advice, we get:

Style 3

// Changed EmployeeServive to return an optional, no more nulls!
Optional<Employee> employee = employeeServive.getEmployee();
employee.ifPresent(e -> System.out.println(e.getId()));

Or a more lengthy snippet

Optional<Employee> employee = employeeServive.getEmployee();
// Sometimes an Employee has forgotten to write an up-to-date timesheet
Optional<Timesheet> timesheet = employee.flatMap(Employee::askForCurrentTimesheet); 
// We don't want to do the heavyweight action of creating a new estimate if it will just be discarded
client.bill(timesheet.orElseGet(EstimatedTimesheet::new));
2 of 11
50

If you're using Optional as a "compatibility" layer between an older API that may still return null, it may be helpful to create the (non-empty) Optional at the latest stage that you're sure that you have something. E.g., where you wrote:

Optional<Employee> employeeOptional = Optional.ofNullable(employeeService.getEmployee());
if(employeeOptional.isPresent()){
    Employee employeeOptional= employeeOptional.get();
    System.out.println(employee.getId());
}

I'd opt toward:

Optional.of(employeeService)                 // definitely have the service
        .map(EmployeeService::getEmployee)   // getEmployee() might return null
        .map(Employee::getId)                // get ID from employee if there is one
        .ifPresent(System.out::println);     // and if there is an ID, print it

The point is that you know that there's a non-null employee service, so you can wrap that up in an Optional with Optional.of(). Then, when you call getEmployee() on that, you may or may not get an employee. That employee may (or, possibly, may not) have an ID. Then, if you ended up with an ID, you want to print it.

There's no need to explicitly check for any null, presence, etc., in this code.

🌐
Medium
medium.com › @m-prakash › java-optional-basics-to-advanced-concepts-eec5542a47b3
Java Optional - Basics to Advanced Concepts | by Prakash Mani | Medium
March 9, 2025 - import java.util.Optional; public class OptionalCheck { public static void main(String[] args) { Optional<String> optional = Optional.of("Java Optional"); if (optional.isPresent()) { System.out.println("Value: " + optional.get()); } optional.ifPresent(value -> System.out.println("Using ifPresent: " + value)); } }
🌐
DZone
dzone.com › coding › java › java 8 optional—replace your get() calls
Java 8 Optional—Replace Your Get() Calls
July 5, 2016 - @Test public void flatMap_whenCardAndLastGiftPresent_thenName(){ Gift mockedGift = mock(Gift.class); when(mockedGift.getName()).thenReturn("Biography of Guybrush Threepwood"); LoyaltyCard mockedCard = mock(LoyaltyCard.class); when(mockedCard.getLastGift()).thenReturn(Optional.of(mockedGift)); Optional<LoyaltyCard> card = Optional.of(mockedCard); String giftName = card.flatMap(LoyaltyCard::getLastGift) .map(Gift::getName) .orElse(""); assertEquals("Biography of Guybrush Threepwood", giftName); } Writing this solution by using isPresent/get would have meant using a nested if: one for check that card was present and another of checking the gift. Harder to read, easier to fail. Unfortunately this is yet to come It will be available in Java 9.
🌐
Community Platform
wearecommunity.io › communities › java_americas › articles › 3846
A better way to use Optional.
In this article, we explore a smarter approach to harnessing the power of Java's Optional class. Discover how functional programming techniques can simplify your code, enhance readability, and make your applications more robust. Say goodbye to lengthy null checks and hello to a more elegant ...