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

Copypublic 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
🌐
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 - Using flatMap() with optionals is similar to using map(), with one important difference: if your transformation closure returns an optional, flatMap() will combine that optional with the existing optional, whereas map() will keep them both. Here’s a practical example so you can see the difference:
🌐
Baeldung
baeldung.com › home › java › java streams › the difference between map() and flatmap()
The Difference Between map() and flatMap() | Baeldung
November 10, 2025 - Let’s see another example to get a better understanding of this situation: assertEquals(Optional.of(Optional.of("STRING")), Optional .of("string") .map(s -> Optional.of("STRING"))); As we can see, we end up with the nested structure ...
🌐
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 - class Test { public static void main(String[] args) { Student student = new Student("John", "Smith", 8); student.setAddress(Optional.of("5th Avenue, New York")); Optional<Student> studentOptional = Optional.ofNullable(student); studentOptional .filter(s1 -> s1.getGrade() > 7) // returns Optional<Student[fName, lName, grade, Optional<String> address]> .flatMap(s1 -> s1.getAddress()) // returns Optional<String> .ifPresent(item -> System.out.println(item)); } }
🌐
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.
🌐
KapreSoft
kapresoft.com › java › 2023 › 12 › 08 › java-optional-map-vs-flatmap.html
Java Optional • map() vs flatMap() | KapreSoft
December 8, 2023 - Here’s a simplified representation of the flatMap() method: Optional<T> optional = ...
🌐
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.
Find elsewhere
🌐
Medium
medium.com › @reetesh043 › java-stream-map-vs-flatmap-60a10e666c75
Exploring the Differences: Java map vs. flatMap | by Reetesh Kumar | Medium
October 4, 2024 - Optional<String> optionalString = Optional.of("Hello"); Optional<Integer> stringLength = optionalString.map(String::length); In this example, the optionalString contains the value "Hello", so the map() the operation will calculate its length ...
🌐
Medium
medium.com › @AlexanderObregon › javas-flatmap-method-explained-3ab4cfc90e64
Java’s flatMap() Method Explained | Medium
October 23, 2024 - By using flatMap(), you can unwrap the Optional, process the stream or collection it holds, and continue working with a flat stream of data. For example, let’s say you have an Optional<List<String>>, where the list might be empty or non-existent.
🌐
Medium
cinish.medium.com › core-java-optional-flatmap-method-d5063c35d56b
Core Java:Optional flatmap method | by Learn | Medium
August 12, 2025 - package com.core.java.functional; import java.util.Optional; public class Citizen { class Continent { public Continent(String name) { this.name = name; } public String name; public Country country; } class Country { public Country(String name) { this.name = name; } public String name; public State state; } class State { public State(String name) { this.name = name; } public String name; public City city; } class City { public City(String name) { this.name = name; } public String name; public Suburb suburb; } class Suburb { public Suburb(String name) { this.name = name; } public String name; pu
🌐
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.
🌐
Medium
medium.com › @AlexanderObregon › javas-optional-map-method-explained-0a19206d6704
Java’s Optional.map() Method Explained | Medium
November 9, 2024 - Let’s revisit the User example, but this time assume we want the city name in uppercase. We can apply both transformations seamlessly with map(): Optional<String> upperCaseCity = user .flatMap(User::getProfile) .flatMap(Profile::getAddress) .map(Address::getCity) .map(String::toUpperCase); upperCaseCity.ifPresent(System.out::println); // Prints the city in uppercase if present
🌐
Huong Dan Java
huongdanjava.com › home › flatmap() method of optional object in java
flatMap() method of Optional object in Java - Huong Dan Java
January 5, 2021 - As you all know, the Optional object ... Optional<Optional<String>>. To resolve this problem, Java introduces us to the flatMap() method so that Optional’s data type is simpler: Optional<String> for example....
🌐
DZone
dzone.com › coding › javascript › understanding flatmap
Understanding flatMap
January 8, 2018 - Function<String, Optional<Long>> toLongOpt = Long::parseLongOpt; Optional<String> someString = Optional.of("12L"); Optional<Long> someLong = someString.flatMap(toLongOpt); For Stream, we can use it in a situation where the function we want to ...
🌐
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 · Raw · flatmap_optionals.java · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
🌐
Steinar Bangs blogg
steinar.bang.priv.no › 2022 › 01 › 18 › chaining-optionals-using-flatmap-and-map
Chaining Optionals using flatMap and map | Steinar Bangs blogg
January 23, 2022 - The blog post How I learnt to like Optional shows an example of how to chain Optional values safely, using Optional.orElse() to provide empty objects for the next level in the chain. This blog post uses Optional.flatMap() and Optional.map(), to achieve the same thing, without having to create the empty objects, and without doing any…
🌐
Baeldung
baeldung.com › home › java › java streams › filtering a stream of optionals in java
Filtering a Stream of Optionals in Java | Baeldung
January 8, 2024 - List<String> filteredList = listOfOptionals.stream() .flatMap(o -> o.map(Stream::of).orElseGet(Stream::empty)) .collect(Collectors.toList()); All this will get quite simplified with the arrival of Java 9 that adds a stream() method to Optional.