DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • The Long Road to Java Virtual Threads
  • The Complete Guide to Stream API and Collectors in Java 8
  • Optimizing Java Applications: Parallel Processing and Result Aggregation Techniques
  • Functional Approach To String Manipulation in Java

Trending

  • Distributed Consensus: Paxos vs. Raft and Modern Implementations
  • Securing the Future: Best Practices for Privacy and Data Governance in LLMOps
  • Driving DevOps With Smart, Scalable Testing
  • Memory Leak Due to Time-Taking finalize() Method
  1. DZone
  2. Coding
  3. JavaScript
  4. Understanding flatMap

Understanding flatMap

Taking a walk on Java's functional side? Here are a few good things to know about how flatMap works and what it offers for Optionals and Streams.

By 
Paweł Szeliga user avatar
Paweł Szeliga
·
Jan. 08, 18 · Tutorial
Likes (19)
Comment
Save
Tweet
Share
38.1K Views

Join the DZone community and get the full member experience.

Join For Free

Have you ever scrolled someone’s code and bumped into this weird method called flatMap, not knowing what it actually does from the context? Or maybe you compared it with method map but didn’t really see much difference? If that is the case, then this article is for you. 

flatMap is extremly useful when you try to do proper functional programming. In Java, it usually means using Streams and Optionals — concepts introduced in version 8. These two types can be thought of as some kind of wrapper over a type that adds some extra behaviour — Stream<T> wrapps type T, allowing you to store any number of elements of type T inside, whereas Optional<T> wraps some type T to explicitly say that the element of that type may or may not be present inside.

Both of them share the methods map and flatMap.

Before we move on, I want to make sure you understand what the map method is doing. It basically allows you to apply the method to the element inside the wrapper and possibly change its type:

Function<String, Long> toLong = Long::parseLong; // function that maps String to Long

Optional<String> someString = Optional.of("12L");
Optional<Long> someLong = someString.map(toLong); //aplying the function to the possible String inside

Stream<String> someStrings = Stream.of("10L", "11L");
Stream<Long> someLongs = someStrings.map(toLong); //applying the function to all Strings inside


After applying the function toLong to our wrappers, their inner types change to the second type of the toLong signature (the result type). 

Let’s examine the function Long::parseLong. If we call it using a string that is not actually a valid long, it will throw NumberFormatException. But what if Java's designers decide to implement it so it returns Optional<Long> instead of just Long and removed the exception? Our code for the Optional part would look like:

Function<String, Optional<Long>> toLongOpt = Long::parseLongOpt;//method I made up

Optional<String> someString = Optional.of("12L");
Optional<Optional<Long>> someLong = someString.map(toLongOpt); //:<


Wow, that is nasty! When we applied the new method to our wrapper, the inner type was changed from String to Optional<Long> (the result type of toLongOpt that we applied). We don’t really need to have a double Optional because just one is perfectly fine. Now, to get the value, we need to extract it twice, not mentioning how it would look like when we want to map it again without unwrapping… To restore it to the single type, we would need to write a method like this one:

public static <T> Optional<T> flatten(Optional<Optional<T>> optional) {
    return optional.orElse(Optional.empty());
}


This method will flatten our Optional<Optional<T>> to Optional<T> without changing the inner value. The code will look like this:

Function<String, Optional<Long>> toLongOpt = Long::parseLongOpt;

Optional<String> someString = Optional.of("12L");
Optional<Long> someLong = flatten(someString.map(toLongOpt));


This is exactly what the method flatMap is doing. It first applies the function returning another Optional to the object inside (if present) and then flattens the result before returning it, so you don’t have to do it yourself. This is how we can use it:

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 map our elements with returns the Stream. (example signature: Function<String, Stream<Long>>).

That’s it. Just remember that flatMap = map + flatten.

If you want to, dive into the topic and read about the Functor and Monad concepts and the relationship between them. 

Element Concept (generic programming) Stream (computing) Strings Data Types Java (programming language) Extract Functor

Published at DZone with permission of Paweł Szeliga. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • The Long Road to Java Virtual Threads
  • The Complete Guide to Stream API and Collectors in Java 8
  • Optimizing Java Applications: Parallel Processing and Result Aggregation Techniques
  • Functional Approach To String Manipulation in Java

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!