Use map if the function returns the object you need or flatMap if the function returns an Optional. For example:

public static void main(String[] args) {
  Optional<String> s = Optional.of("input");
  System.out.println(s.map(Test::getOutput));
  System.out.println(s.flatMap(Test::getOutputOpt));
}

static String getOutput(String input) {
  return input == null ? null : "output for " + input;
}

static Optional<String> getOutputOpt(String input) {
  return input == null ? Optional.empty() : Optional.of("output for " + input);
}

Both print statements print the same thing.

Answer from assylias on Stack Overflow
🌐
Swift Forums
forums.swift.org › using swift
Optional .map() vs. flatMap(): why not always use .flatMap()? - Using Swift - Swift Forums
March 24, 2021 - It seems Optional.map() when the transform closure returns nil, then result is Optional(nil) , which is same as Optional.some(nil)? Still a nil but is wrap up an optional? But Optional.flatMap() when the transform closure returns nil, the result is just nil, which is simpler.
🌐
Baeldung
baeldung.com › home › java › java streams › the difference between map() and flatmap()
The Difference Between map() and flatMap() | Baeldung
November 10, 2025 - Both methods work similarly for Optional. The map() method wraps the underlying sequence in a Stream instance, whereas the flatMap() method allows avoiding nested Stream<Stream<R>> structure.
🌐
Blogger
java8example.blogspot.com › 2019 › 08 › optional-flatmap.html
Java 8 Optional flatMap() Method Example Java8Example
August 7, 2019 - If a value is present, returns the result of applying the given Optional-bearing mapping function to the value, otherwise returns an empty Optional. This method is similar to map(Function), but the mapping function is one whose result is already an Optional, and if invoked, flatMap does not wrap it within an additional Optional.
🌐
Apple Developer
developer.apple.com › documentation › swift › optional › flatmap(_:)
flatMap(_:) | Apple Developer Documentation
Evaluates the given closure when this instance is not , passing the unwrapped value as a parameter.
🌐
Hacking with Swift
hackingwithswift.com › example-code › language › how-to-use-flatmap-with-an-optional-value
How to use flatMap() with an optional value - free Swift example code and tips
May 28, 2019 - The flatMap() method of optionals allows you to transform the optional if it has a value, or do nothing if it is empty.
🌐
Apps Developer Blog
appsdeveloperblog.com › home › java › functional programming in java › optional – map() and flatmap() operations
Optional - map() and flatMap() operations - Apps Developer Blog
August 10, 2022 - public <U> Optional<U> flatMap(Function<? super T,Optional<U> mapper) Description: If a value is present, apply the provided Optional-bearing mapping function to it, and return that result.
🌐
Medium
medium.com › @AlexanderObregon › javas-optional-map-method-explained-0a19206d6704
Java’s Optional.map() Method Explained | Medium
November 9, 2024 - flatMap() unwraps the nested Optional and allows the code to proceed without creating layers of optionals.
Find elsewhere
🌐
Medium
cinish.medium.com › core-java-optional-flatmap-method-d5063c35d56b
Core Java:Optional flatmap method | by Learn | Medium
August 12, 2025 - The following flatMap focused idiom works well for all scenarios irrespective of at what level the value is missing. Optional.ofNullable(full) .flatMap(emp -> Optional.ofNullable(emp.getDepartment())) .flatMap(dept -> Optional.ofNullable(dept.getName())) .orElse("department name not found") ;
🌐
KapreSoft
kapresoft.com › java › 2023 › 12 › 08 › java-optional-map-vs-flatmap.html
Java Optional • map() vs flatMap() | KapreSoft
December 8, 2023 - We create an Optional<String> named optionalString containing the string “Hello, World!”. We use flatMap() to transform the string into an Optional<Integer> representing its length.
🌐
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
August 30, 2016 - However, on trying to explain what the flatMap does and why we need it, I stumbled upon an unexpected feature of Java. You might have already discovered it when experimenting with the codebase. It turns out the following is functionally equivalent, as proven by the tests we had written before we tried the whole refactoring: return Optional.ofNullable(location) .map(loc -> officeRepository.findFor(loc.getZipCode())) .orElseGet(() -> retrieveDefaultOffice());
🌐
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
abdulahd1996.medium.com › understanding-flatmap-on-optionals-5acd773a86e6
Understanding FlatMap on Optionals | by abdul ahad | Medium
November 25, 2024 - The flatMap function for optionals in Swift is used to transform an optional value and return a new optional. It is particularly useful when the transformation itself might return an optional, and…
🌐
Baeldung
baeldung.com › home › java › core java › guide to java optional
Guide To Java Optional | Baeldung
February 15, 2026 - Just like the map() method, we also have the flatMap() method as an alternative for transforming values. The difference is that map transforms values only when they are unwrapped whereas flatMap takes a wrapped value and unwraps it before transforming it. Previously, we created simple String and Integer objects for wrapping in an Optional instance.
🌐
GitHub
gist.github.com › Allan-Gong › 548fea5f9eb2e71c0470cee4be593a6e
Options to flatMap a list of Optionals in Java8 · GitHub
Options to flatMap a list of Optionals in Java8. GitHub Gist: instantly share code, notes, and snippets.
🌐
Codingjunkie
codingjunkie.net › working-with-java8-optionals
Working With Java 8 Optionals - Random Thoughts on Coding
October 30, 2015 - Optional.empty() : Optional.of(s.toUpperCase()); Optional<String> word = Optional.of("apple"); Optional<Optional<String>> optionalOfOptional = word.map(upperCaseOptionalString); Optional<String> upperCasedOptional = word.flatMap(upperCaseOptionalString); assertThat(optionalOfOptional.get().get(), is("APPLE")); assertThat(upperCasedOptional.get(), is("APPLE")); }
🌐
Kodeco
kodeco.com › books › swift-cookbook › v1.0 › chapters › 8-use-optional-map-flatmap
Swift Cookbook, Chapter 8: Use Optional Map & FlatMap | Kodeco
In this example, the map function takes a closure that multiplies the optional integer by 2 (if it is not nil). The flatMap function can be used to flatten a nested optional.
🌐
Microsoft Learn
learn.microsoft.com › en-us › dotnet › api › java.util.optional.flatmap
Optional.FlatMap(IFunction) Method (Java.Util) | Microsoft Learn
This method is similar to #map(Function), but the mapping function is one whose result is already an Optional, and if invoked, flatMap does not wrap it within an additional Optional.
🌐
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, apply the provided Optional-bearing mapping function to it, return that result, otherwise return an empty Optional. This method is similar to map(Function), but the provided mapper is one whose result is already an Optional, and if invoked, flatMap does not wrap it with ...