findFirst() gives you an Optional and you then have to decide what to do if it's not present. So findFirst().orElse(null) should give you the object or null if it's not present

You could just do a .get() on the Optional, but that could be regarded as poor practice since get() will throw an exception if Optional has no content. You should normally assert presence/absence of the Optional and decide what to do in each case (that's why it's there - so that you know something is truly optional and you have to determine what to do)

If you have an action you want to perform on object presence, and you don't want to do anything on absence, you can call .ifPresent() and provide a lambda as an argument. That will be called with the contained object, if present.

As of Java 9, a further solution would be to use Optional.ifPresentOrElse()

Answer from Brian Agnew on Stack Overflow
🌐
DZone
dzone.com › coding › java › how to use optionals in java
How to Use Optionals in Java
June 16, 2020 - We will instead see a compilation error alerting us that an object of type Optional<Foo> cannot be cast to Foo since the return type of doSomething is Optional<Foo> and the type of foo is Foo. Thus, we must call a method such as orElse or orElseThrow—or get, but we will see later why that should not be the first choice — in order to convert the Optional<Foo> object to a Foo object.
🌐
Develpreneur
develpreneur.com › home › introduction to the java optional class
Introduction to the Java Optional Class
November 15, 2022 - In our last example, we will look at using the stream() method to map() our optional objects into their object counterparts. So this could be useful for JPA Entities or just plain old objects. We can also use the filter method to remove nulls or pull out the specific data we want from within our streams. Look at using stream() & map() to convert a List<String> to List<Optional<String>>.
🌐
Tom Gregory
tomgregory.com › gradle › java-optional
Optional in Java: Everything You Need To Know | Tom Gregory
July 17, 2022 - If you'd like to convert a value contained within an Optional to another type of object, then call map passing a function.
🌐
Baeldung
baeldung.com › home › java › core java › guide to java optional
Guide To Java Optional | Baeldung
February 15, 2026 - In the above example, we use only two lines of code to replace the five that worked in the first example: one line to wrap the object into an Optional object and the next to perform implicit validation as well as execute the code.
🌐
X-Team
x-team.com › blog › using-optional-to-transform-your-java-code
Using Optional to Transform Your Java Code | X-Team
January 2, 2025 - In terms of increasing readability or safety, this use of Optional does little. We still have that if/else block, and it’s still possible to try to use the reference without making sure it’s there. You can modify the code to call get() without the check. It will compile and then throw a NoSuchElementException. We exchanged one exception for another. Before we move on, let’s create an object that returns an Optional.
🌐
LinkedIn
linkedin.com › pulse › optional-java-8-example-terala-chittibabu
Optional in Java 8 with example
July 12, 2022 - An Optional can be created by calling its static of method supplying it the object that the Optional will hold or the object wrapped by Optional. ... If the object provided to of is null, then it will raise a NullPointerException.
🌐
Algoclinic
algoclinic.com › create-an-optional-object-from-a-nullable-object.html
Create an Optional Object from a Nullable Object - Sumiya
Code Snippets that follow it provide how we provide methods that convert this Nullable object to an Optional object. import java.util.Optional; public class Name { private String middleName; public void setMiddleName(String middleName) { this.middleName = middleName; } /** * Convert the String object to an Optional<String> object * * @return an Optional String */ public Optional<String> getOptionalMiddleName() { return Optional.ofNullable(middleName); } /** * * @return the middle name when it exists, or an empty string when it * doesn't */ public String getMiddleName() { return getOptionalStri
🌐
CalliCoder
callicoder.com › java-8-optional-tutorial
Java Optional Tutorial with Examples | CalliCoder
February 18, 2022 - Let’s say you have an Optional object of User. You want to check its gender and call a function if it’s a MALE.
Find elsewhere
🌐
Stacktraceguru
stacktraceguru.com › home › access value from optional object
Java 8 Optional ways to access value from optional object
November 7, 2018 - Public method that almost similar to orElse with small difference, Unlike orElse(..) method orElseGet takes the supplier function as argument and this function will be executed if Optional is empty.
🌐
DZone
dzone.com › coding › languages › java optional objects
Java Optional Objects
April 17, 2013 - Sign in to see who liked this post! ... Join the DZone community and get the full member experience. Join For Free · In this post I present several examples of the new Optional objects in Java 8 and I make comparisons with similar approaches in other programming languages, particularly the functional programming language SML and the JVM-based programming language Ceylon, this latter currently under development by Red Hat.
🌐
Mkyong
mkyong.com › home › java8 › java 8 – convert optional to string
Java 8 - Convert Optional<String> to String - Mkyong.com
February 23, 2020 - In Java 8, we can use .map(Object::toString) to convert an Optional<String> to a String.
🌐
Medium
medium.com › @uvrajanshuman › optional-in-java-8-ffcf45e01602
Optional in Java 8. Optional is a generic class defined in… | by Anshuman Yuvraj | Medium
October 2, 2023 - Optional in Java 8 Optional is a generic class defined in the java.util package, that got introduced in Java 8. It facilitates the handling of potentially absent values in a more concise and …
🌐
Baeldung
baeldung.com › home › java › java list › convert an optional to an arraylist in java
Convert an Optional to an ArrayList in Java | Baeldung
March 7, 2025 - First, we create an Optional object named optionalValue with a value of “Hello, World!”. Next, we convert the Optional to an ArrayList using a Java Stream. We call the stream() method on optionalValue to obtain a stream of its elements.
🌐
Oracle
docs.oracle.com › en › java › javase › 17 › docs › api › java.base › java › util › Optional.html
Optional (Java SE 17 & JDK 17)
April 21, 2026 - The other object is considered equal if: ... Returns the hash code of the value, if present, otherwise 0 (zero) if no value is present. ... Returns a non-empty string representation of this Optional suitable for debugging. The exact presentation format is unspecified and may vary between implementations and versions. ... If a value is present the result must include its string representation in the result. Empty and present Optionals must be unambiguously differentiable.
🌐
Medium
medium.com › swlh › playing-with-java-optional-70ffecb9da33
Playing With Java Optional. A container object which may or may not… | by Sofiene Ben Khemis | The Startup | Medium
December 15, 2021 - I imagine you might be thinking something like, “Yes, I agree, NullPointerExceptions is a pain for any Java developer, novice or expert, but there’s not much we can do about them.“ This is a common feeling in the programming world. Until Java 8 introduced Optional. Optional allows an object to wrap those nullable values.
Top answer
1 of 2
3

It’s not completely clear what you want the result to be, in particular not what you want in case one of the Optionals is empty. For this code snippet I have assumed that you want to leave those entries out.

    Map<Object, Optional<Object>> originalMap = Map.of("Key 1", Optional.of(Integer.valueOf(2)),
            Integer.valueOf(3), Optional.empty(),
            "Key 4", Optional.of("Value 4"));
    Map<Object, Object> targetMap = originalMap.entrySet()
            .stream()
            .filter(e -> e.getValue().isPresent())
            .collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().orElseThrow()));
    System.out.println(targetMap);

Output is:

{Key 1=2, Key 4=Value 4}

I usually tell folks to avoid Optional.isPresent() as low-level. In this case I would use it. I don’t consider it bad code on my part, but rather a sign of bad API design as you already said.

In case you prefer not to use Optional.isPresent(), there is a way without it. The code gets less readable IMHO:

    Map<Object, Object> targetMap = originalMap.entrySet()
            .stream()
            .flatMap(e -> e.getValue().stream().map(v -> Map.entry(e.getKey(), v)))
            .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

The result is the same as before.

2 of 2
1

If the output map had the same type you could use replaceAll overwrite the values in place.

Since the input and output maps have different types, you can use a stream to map the entries and create a new map:

Map<Object, Object> newMap = itemsMap
    .entrySet()
    .stream()
    .collect(Collectors.toMap(
        e -> e.getKey(),
        e -> e.getValue().orElseThrow(
            () -> new WhateverMyExceptionIs("Exception Message")
        )
    ));
🌐
Medium
sohailshah20.medium.com › using-optionals-in-java-the-right-way-f32d7ed46d93
Using Optional in Java the right way | by Sohail Shah | Medium
August 21, 2023 - The java.util.Optional<T> class is a generic type class that contains only one value of type T. Its purpose is to provide a safer alternative to reference objects of a type T that can be null.