If you have no idea what can be null, or want to check everything for null, the only way is to chain calls to Optional.map:

If a value is present, apply the provided mapping function to it, and if the result is non-null, return an Optional describing the result. Otherwise return an empty Optional.

As such, if the mapper return null, an empty Optional will be returned, which allows to chain calls.

Optional.ofNullable(insight)
        .map(i -> i.getValues())
        .map(values -> values.get(0))
        .map(v -> v.getValue())
        .orElse(0);

The final call to orElse(0) allows to return the default value 0 if any mapper returned null.

Answer from Tunaki on Stack Overflow
🌐
Baeldung
baeldung.com › home › java › core java › guide to java optional
Guide To Java Optional | Baeldung
February 15, 2026 - public boolean priceIsInRange2(Modem modem2) { return Optional.ofNullable(modem2) .map(Modem::getPrice) .filter(p -> p >= 10) .filter(p -> p <= 15) .isPresent(); } The map call is simply used to transform a value to some other value.
🌐
Medium
medium.com › @AlexanderObregon › javas-optional-map-method-explained-0a19206d6704
Java’s Optional.map() Method Explained | Medium
November 9, 2024 - With Optional.map(), we can accomplish this in a streamlined way: public class User { private Profile profile; // constructor and other methods public Optional<Profile> getProfile() { return Optional.ofNullable(profile); } } public class Profile { private Address address; // constructor and other methods public Optional<Address> getAddress() { return Optional.ofNullable(address); } } public class Address { private String city; // constructor and getters } // Creating an Optional User instance Optional<User> user = Optional.ofNullable(getUser()); // Using flatMap to safely access nested properties Optional<String> city = user .flatMap(User::getProfile) .flatMap(Profile::getAddress) .map(Address::getCity); city.ifPresent(System.out::println); // Prints the city if present
Discussions

How to idiomatically map() a nullable reference
Please ensure that: Your code is properly formatted as code block - see the sidebar (About on mobile) for instructions You include any and all error messages in full You ask clear questions You demonstrate effort in solving your question/problem - plain posting your assignments is forbidden (and such posts will be removed) as is asking for or giving solutions. Trying to solve problems on your own is a very important skill. Also, see Learn to help yourself in the sidebar If any of the above points is not met, your post can and will be removed without further warning. Code is to be formatted as code block (old reddit: empty line before the code, each code line indented by 4 spaces, new reddit: https://i.imgur.com/EJ7tqek.png ) or linked via an external code hoster, like pastebin.com, github gist, github, bitbucket, gitlab, etc. Please, do not use triple backticks (```) as they will only render properly on new reddit, not on old reddit. Code blocks look like this: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World!"); } } You do not need to repost unless your post has been removed by a moderator. Just use the edit function of reddit to make sure your post complies with the above. If your post has remained in violation of these rules for a prolonged period of time (at least an hour), a moderator may remove it at their discretion. In this case, they will comment with an explanation on why it has been removed, and you will be required to resubmit the entire post following the proper procedures. To potential helpers Please, do not help if any of the above points are not met, rather report the post. We are trying to improve the quality of posts here. In helping people who can't be bothered to comply with the above points, you are doing the community a disservice. I am a bot, and this action was performed automatically. Please contact the moderators of this subreddit if you have any questions or concerns. More on reddit.com
🌐 r/javahelp
9
2
October 7, 2023
Using Java 8 Optional for safe fetching from Map - Stack Overflow
I understand that Java 8's Optional brings the required behavior. Is there a way to use Optional to elegantly get the data instead of using containsKey checks? ... Optional is just a container for a possible value or null. You'll still have to check the map for your desired key. Keep it Simple Soldier. ... Seems like you're looking for Optional.ofNullable... More on stackoverflow.com
🌐 stackoverflow.com
Why does Optional require a non-null value?
Optional.of(T) exists to allow some knowledge to be passed on. I see .of(T) as a way to make sure that the parameter is not null. If it is null, then I might have a bug somewhere, and I'll know it. While I will not know it if I use ofNullable (or at least, it'll be much harder to check). More on reddit.com
🌐 r/java
124
69
June 13, 2024
Why exactly does Brian Goetz not recommend the use of Optional everywhere a value could be null?
The idea with Optional is to force the user of the method to handle the output straight away. Being able to pass that value around is against the point of using an Optional in the first place. For example, you have a method that calls an API. If it returns empty, you should either throw an exception, or fill in some default value. If it returns a value, then unpack it. You should not have an Optional going forward. More on reddit.com
🌐 r/java
285
123
June 2, 2023
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › util › Optional.html
Optional (Java Platform SE 8 )
April 21, 2026 - an Optional describing the value of this Optional if a value is present and the value matches the given predicate, otherwise an empty Optional ... If a value is present, apply the provided mapping function to it, and if the result is non-null, return an Optional describing the result.
🌐
Readthedocs
java8tips.readthedocs.io › en › stable › optional.html
10. Handling nulls with Optional — Java 8 tips 1.0 documentation
Stream can contain huge number of elements where using primitives can save time as well as space but an Optional can have at most single value and primitive optional will not employ much difference in fact it will stop you to use common methods like map, filter etc. ... Optionals were designed to handle missing values. These were not intended for use as a field type so it doesn’t implement Serializable. In case you need to have a serializable domain model, implement getter methods returning optionals given below. class Candidate { String name; String spouce; public Optional<String> getSpouse(){ return Optional.ofNullable(spouse); } }
🌐
Verhoevenv
verhoevenv.github.io › 2016 › 08 › 30 › TIL-Optional-map.html
Today I Learned: Java 8's Optional.map is actually flatmap | Vincent Verhoeven's blog
If a value is present, apply the provided mapping function to it, and if the result is non-null, return an Optional describing the result. Otherwise return an empty Optional. It makes total sense for Java. The class invariant is that an Optional can never hold a null value, so either the map ...
🌐
DevTut
devtut.github.io › java › optional.html
Java - Optional
August 30, 2016 - Because Optional.map() (opens new window) returns an empty optional when its mapping function returns null, you can chain several map() operations as a form of null-safe dereferencing. This is also known as Null-safe chaining. ... Any of getBar, getBaz, and toString can potentially throw a NullPointerException. Here is an alternative way to get the value from toString() using Optional: String value = Optional.ofNullable(foo) .map(Foo::getBar) .map(Bar::getBaz) .map(Baz::toString) .orElse("");
🌐
Reddit
reddit.com › r/javahelp › how to idiomatically map() a nullable reference
r/javahelp on Reddit: How to idiomatically map() a nullable reference
October 7, 2023 -

I'm trying to find the idiomatic way of applying a mapping on something which may be null, in a Java 17+ codebase, but where there are sometimes nulls around.

Imagine you have a method like this, where I want to return a path to some file, or null:

Path theSomethingPathOrNull() {
    File theFile = ... something elaborate which may give null
    return theFile.toPath(); // Obviously a problem
}

Now, if only it were Groovy, and I could use:

    return theFile?.toPath()

But alas, this is just Java. Back in the day, we'd have done it with:

    return theFile != null ? theFile.toPath() : null;

But people not used to C would have frowned in the code review. Yeah, they sometimes do.

Now, since this is for "modern" Java, I suppose the idiomatic way would be:

    return Optional.ofNullable(theFile).map(File::toPath).orElse(null);

That's a mouthful. Even with a static import of Optional.ofNullable, it seems noisy.

I could make a nice little helper like this somewhere:

public static <T, U> U mapNullable(T obj, Function<? super T, ? extends U> mapper) {
    Objects.requireNonNull(mapper);
    return obj != null ? mapper.apply(obj) : null;
}

Then I could write:

return mapNullable(theFile, File::toPath);

That would save a few keystrokes, but would people understand it?

Does this helper exist in a commonly used library already?

Any ideas or bikeshed suggestions?

P.S.: I know that the real answer is that I should be returning an Optional instead, but that's not always an option.

Find elsewhere
🌐
Medium
medium.com › @AlexanderObregon › javas-optional-ofnullable-method-explained-1263612e5b22
Java’s Optional.ofNullable() Method Explained | Medium
August 7, 2024 - Example: List<String> names = ... .map(String::toUpperCase) .forEach(System.out::println); In this example, Optional.ofNullable() is used to wrap each name, and flatMap(Optional::stream) is used to filter out the empty Optional objects, ...
🌐
Medium
medium.com › @prawin609 › replacing-nested-if-else-null-checks-with-optional-map-and-filter-in-java-streams-api-6d831fbd81ca
Replacing Nested If-Else Null Checks with Optional, Map, and Filter in Java Streams API | by Prawin Thangaswamy | Medium
September 8, 2024 - Optional.ofNullable(order): Creates an Optional object containing the Order. If order is null, an empty Optional is created. map(Order::getCustomer): Applies the getCustomer() method on the Order object if present.
🌐
X-Team
x-team.com › magazine › using-optional-to-transform-your-java-code
Using Optional to Transform Your Java Code | X-Team
January 2, 2025 - Checking the result of retrieving something from a HashMap is a precaution all Java programmers are accustomed to. ... Let’s start with the most basic use of Optional: using the isPresent() method to check if it is empty. public static void main(String[] args) { HashMap<Integer, String> stringMap = new HashMap<>(); stringMap.put(0, "John Doe"); stringMap.put(1, "Alfred Neuman"); stringMap.put(2, "John Galt"); for (int i = 0; i < 4; i++) { Optional optName = Optional.ofNullable(stringMap.get(i)); if (optName.isPresent()) { System.out.println("Name " + i + " is " + optName.get()); } else { System.out.println("Name " + i + " is not found."); } } }
🌐
Oracle
docs.oracle.com › en › java › javase › 19 › docs › api › java.base › java › util › Optional.html
Optional (Java SE 19 & JDK 19)
December 12, 2022 - If a value is present, returns an Optional describing (as if by ofNullable(T)) the result of applying the given mapping function to the value, otherwise returns an empty Optional.
🌐
Laulem
laulem.com › en › dev › optional-usage-java-tutorial.html
Guide To Java Optional - LauLem.com
November 7, 2024 - String firstName = Optional.ofNullable(element).orElseThrow(); // NoSuchElementException; String firstName2 = Optional.ofNullable(element) .orElseThrow(() -> new Exception("The element must not be empty")); // Exception; Just like Streams, Optional allows filtering the content via a predicate.
🌐
Tabnine
tabnine.com › home › code library
Code Library - Tabnine
July 25, 2024 - Get the answers and suggestions you need from our AI code assistant. Get started in minutes with a free 90 day trial of Tabnine Pro.
🌐
Medium
medium.com › javarevisited › java-null-handling-with-optionals-b2ded1f48b39
Java - Null Handling With Optionals | by Ömer Kurular | Javarevisited | Medium
September 4, 2021 - As we covered Optional methods, we can have a look at some examples in core Java and Spring applications. Imagine we have a class that works as cache and we can get objects with keys of type String. In this case, would not it make perfect sense to use Optionals as we may not have an object associated with a given key? Let’s see it in action · public enum ObjectCache { INSTANCE; private final Map<String, Object> objectMap = new HashMap<>(); public Optional<Object> get(String key) { return Optional.ofNullable(objectMap.get(key)); } public void add(String key, Object value) { objectMap.put(key, value); } public Optional<Object> delete(String key) { return Optional.ofNullable(objectMap.remove(key)); } } In the ObjectCache class, we have three methods that interact with the objectMap.
🌐
Frankel
blog.frankel.ch › optional-nullable-type
Handling null: optional and nullable types
April 3, 2022 - With it, we can rewrite the above null-checking code as: var option = Optional.ofNullable(foo) .map(Foo::getBar) .map(Bar::getBaz) .map(String::toLowerCase); If any of the values in the call chain is null, option is empty.
🌐
Foojay
foojay.io › home › optional in java: a swiss army knife for handling nulls and improving code quality
Optional in Java: A Swiss Army Knife for Handling Nulls and Improving Code Quality
February 20, 2023 - For example, you can use Optional.map() to perform a transformation on a value only if it is present, without having to write an if statement to check for null. Example- String value = null; Optional<String> optionalValue = Optional.ofNulla...