eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – Summer Sale 2026 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:

>> EXPLORE ACCESS NOW

Course – Summer Sale 2026 – NPI (cat=Baeldung)
announcement - icon

Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:

>> EXPLORE ACCESS NOW

eBook – Reactive – NPI(cat= Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

1. Introduction

Spring WebFlux is a reactive programming framework that facilitates asynchronous, non-blocking communication. A key aspect of working with WebFlux is handling Mono objects, representing a single asynchronous result. In real-world applications, we often need to transform one Mono object to another, whether to enrich data, handle external service calls, or restructure the payload.

In this tutorial, we’ll explore how to convert a Mono object into another Mono object using various approaches provided by Project Reactor.

2. Converting Mono Object

Before we explore the various ways to transform Mono objects, let’s set up our coding example. We’ll use book-borrow examples throughout our tutorial to demonstrate different transformation methods. To capture this scenario, we’ll work with three key classes.

User class to represent a library user:

public class User {
    private String userId;
    private String name;
    private String email;
    private boolean active;

    // standard setters and getters
}

Each user is uniquely identified by a userId and has personal details like name and email. Additionally, there’s an active flag to indicate whether the user is currently eligible to borrow books.

Book class to represent the library’s collection of books:

public class Book {
    private String bookId;
    private String title;
    private double price;
    private boolean available;

    //standard setters and getters
}

Each book is identified by a bookId and has attributes like title and price. The available flag indicates whether the book can be borrowed.

BookBorrowResponse class to encapsulate the result of a borrowing operation:

public class BookBorrowResponse {
    private String userId;
    private String bookId;
    private String status;

    //standard setters and getters
}

This class ties together the userId and bookId involved in the process and provides a status field to indicate whether the borrowing was accepted or rejected.

3. Synchronous Transformations with map()

The map operator applies a synchronous function to the data inside Mono. It suits lightweight operations like formatting, filtering, or simple computations. For example, if we want to get the email address from the Mono user, we can use the map to convert it:

@Test
void givenUserId_whenTransformWithMap_thenGetEmail() {
    String userId = "U001";
    Mono<User> userMono = Mono.just(new User(userId, "John", "[email protected]"));
    Mockito.when(userService.getUser(userId))
      .thenReturn(userMono);

    Mono<String> userEmail = userService.getUser(userId)
      .map(User::getEmail);

    StepVerifier.create(userEmail)
      .expectNext("[email protected]")
      .verifyComplete();
}

4. Asynchronous Transformations with flatMap()

The flatMap() method transforms each emitted item from Mono into another Publisher. It’s especially useful when the transformation requires a new asynchronous process, such as making another API call or querying a database. flatMap() flattens the result into a single sequence when the transformation result is a Mono.

Let’s look into our book borrowing system. When a user requests to borrow a book, the system validates the user’s membership status and then checks if the book is available. If both checks pass, the system processes the borrowing request and returns a BookBorrowResponse:

public Mono<BookBorrowResponse> borrowBook(String userId, String bookId) {
    return userService.getUser(userId)
      .flatMap(user -> {
          if (!user.isActive()) {
              return Mono.error(new RuntimeException("User is not an active member"));
          }
          return bookService.getBook(bookId);
      })
      .flatMap(book -> {
          if (!book.isAvailable()) {
              return Mono.error(new RuntimeException("Book is not available"));
          }
          return Mono.just(new BookBorrowResponse(userId, bookId, "Accepted"));
      });
}

In this example, the operations, such as retrieving user and book details, are asynchronous and return Mono objects. Using flatMap(), we can chain these operations in a readable and logical manner, without nesting multiple levels of Mono. Each step in the sequence depends on the result of the previous step. For example, book availability is only checked if the user is active. flatMap() ensures we can make these decisions dynamically while keeping the flow reactive.

5. Reusable Logic with transform() Method

The transform() method is a versatile tool that allows us to encapsulate reusable logic. Instead of repeating transformations across multiple parts of the application, we can define them once and apply them whenever required. This promotes code reusability, separation of concerns, and readability.

Let’s look into an example where we need to return the final price of a book after applying tax and discount:

public Mono<Book> applyDiscount(Mono<Book> bookMono) {
    return bookMono.map(book -> {
        book.setPrice(book.getPrice() - book.getPrice() * 0.2);
        return book;
    });
}

public Mono<Book> applyTax(Mono<Book> bookMono) {
    return bookMono.map(book -> {
        book.setPrice(book.getPrice() + book.getPrice() * 0.1);
        return book;
    });
}

public Mono<Book> getFinalPricedBook(String bookId) {
    return bookService.getBook(bookId)
      .transform(this::applyTax)
      .transform(this::applyDiscount);
}

In this example applyDiscount() method applies a discount of 20% and the applyTax() method applies a 10% Tax. The transform method applies both methods in the pipeline and returns Mono of Book with the final price.

6. Merging Data from Multiple Sources

The zip() method combines multiple Mono objects and produces a single result. It does not merge results concurrently but waits for all Mono objects to emit before applying the combinator function.

Let’s reiterate our book borrow example, where we fetch user info and book info to create a BookBorrowResponse:

public Mono<BookBorrowResponse> borrowBookZip(String userId, String bookId) {
    Mono userMono = userService.getUser(userId)
      .switchIfEmpty(Mono.error(new RuntimeException("User not found")));
    Mono bookMono = bookService.getBook(bookId)
      .switchIfEmpty(Mono.error(new RuntimeException("Book not found")));
    return Mono.zip(userMono, bookMono,
      (user, book) -> new BookBorrowResponse(userId, bookId, "Accepted"));
}

In this implementation, the zip() method ensures the user and book information is available before creating the response. If the user or book retrieval fails (e.g. if the user doesn’t exist or the book is not available), the error will propagate, and the combined Mono terminates with the appropriate error signal.

7. Conditional Transformations

By combining filter() and switchIfEmpty() methods, we can apply conditional logic to transform a Mono object based on a predicate. If the predicate is true, the original Mono is returned and if it’s false, the Mono switches to a different one provided by switchIfEmpty() or vice versa.

Let’s consider a scenario where we want to apply a discount only if the user is active, else return without discount:

public Mono<Book> conditionalDiscount(String userId, String bookId) {
    return userService.getUser(userId)
      .filter(User::isActive)
      .flatMap(user -> bookService.getBook(bookId).transform(this::applyDiscount))
      .switchIfEmpty(bookService.getBook(bookId))
      .switchIfEmpty(Mono.error(new RuntimeException("Book not found")));
}

In this example, we fetch a Mono of User using userId. The filter method checks if the user is active. If the user is active, we return a Mono of Book after applying the discount. If the user is inactive, the Mono becomes empty, and the switchIfEmpty() method kicks in to fetch the book without applying a discount. Finally, if the book itself does not exist, another switchIfEmpty() ensures an appropriate error is propagated, making the entire flow robust and intuitive.

8. Error Handling During Transformations

Error handling ensures resilience in transformations, allowing graceful fallback mechanisms or alternative data sources. When a transformation fails, proper error handling helps in recovering gracefully, logging issues, or returning alternative data.

The onErrorResume() method is used to recover from errors by providing an alternative Mono. This is especially useful when we want to provide default data or fetch data from an alternative source.

Let’s revisit our book borrow example; if any error is thrown while fetching either the User or Book object, we handle the failure gracefully by returning a BookBorrowResponse object with “Rejected” status:

public Mono<BookBorrowResponse> handleErrorBookBorrow(String userId, String bookId) {
    return borrowBook(userId, bookId)
      .onErrorResume(ex -> Mono.just(new BookBorrowResponse(userId, bookId, "Rejected")));
}

This error-handling strategy ensures that even in failure scenarios, the system responds predictably and maintains a seamless user experience.

9. Best Practices for Converting Mono Objects

When converting Mono objects, it is essential to follow some best practices to ensure our reactive pipelines are clean, efficient, and maintainable. When we need simple, synchronous transformations like enriching or modifying data, the map() method is a perfect choice, while flatMap() is ideal for tasks involving asynchronous workflows, such as calling an external API or querying databases. To keep pipelines clean and reusable, we encapsulate logic with the transform() method, promoting modularity and separation of concerns. To maintain readability, we should prefer chaining over nesting operations.

Error handling plays a key role in ensuring resilience. By using methods like onErrorResume(), we can gracefully manage errors by providing fallback responses or alternative data sources. Finally, validating inputs and outputs at every stage helps prevent issues from propagating downstream, ensuring a robust and scalable pipeline.

10. Conclusion

In this tutorial, we’ve learned various ways to convert one Mono object to another. It’s essential to understand the right operator for the job, be it map(), flatMap(), or transform(). With these techniques and applying best practices, we can build a flexible and maintainable reactive pipeline in Spring WebFlux.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – Summer Sale 2026 – NPI EA (cat= Baeldung)
announcement - icon

Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:

>> EXPLORE ACCESS NOW

Course – Summer Sale 2026 – NPI (All)
announcement - icon

Yes, we're now running our only Summer Sale. All Courses are 30% off until 20th July, 2026:

>> EXPLORE ACCESS NOW

eBook Jackson – NPI EA – 3 (cat = Jackson)