Partner – Microsoft – NPI EA (cat = Baeldung)
announcement - icon

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, visit the documentation page.

You can also ask questions and leave feedback on the Azure Container Apps GitHub page.

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

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, you can get started over on the documentation page.

And, you can also ask questions and leave feedback on the Azure Container Apps GitHub page.

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

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag=Microservices)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

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 – MongoDB – NPI EA (tag=MongoDB)
announcement - icon

Traditional keyword-based search methods rely on exact word matches, often leading to irrelevant results depending on the user's phrasing.

By comparison, using a vector store allows us to represent the data as vector embeddings, based on meaningful relationships. We can then compare the meaning of the user’s query to the stored content, and retrieve more relevant, context-aware results.

Explore how to build an intelligent chatbot using MongoDB Atlas, Langchain4j and Spring Boot:

>> Building an AI Chatbot in Java With Langchain4j and MongoDB Atlas

Partner – LambdaTest – NPI EA (cat=Testing)
announcement - icon

Accessibility testing is a crucial aspect to ensure that your application is usable for everyone and meets accessibility standards that are required in many countries.

By automating these tests, teams can quickly detect issues related to screen reader compatibility, keyboard navigation, color contrast, and other aspects that could pose a barrier to using the software effectively for people with disabilities.

Learn how to automate accessibility testing with Selenium and the LambdaTest cloud-based testing platform that lets developers and testers perform accessibility automation on over 3000+ real environments:

Automated Accessibility Testing With Selenium

eBook – Java Streams – NPI (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

1. Overview

In this tutorial, we’ll review the method Stream::mapMulti introduced in Java 16. We’ll write simple examples to illustrate how to use it. In particular, we’ll see that this method is similar to Stream::flatMap. We’ll cover under what circumstances we prefer to use mapMulti over flatMap.

Be sure to check out our articles on Java Streams for a deeper dive into the Stream API.

2. Method Signature

Omitting the wildcards, the mapMulti method can be written more succinctly:

<R> Stream<R> mapMulti​(BiConsumer<T, Consumer<R>> mapper)

It’s a Stream intermediate operation. It requires as a parameter the implementation of a BiConsumer functional interface. The implementation of the BiConsumer takes a Stream element T, if necessary, transforms it into type R, and invokes the mapper’s Consumer::accept.

Inside Java’s mapMulti method implementation, the mapper is a buffer that implements the Consumer functional interface.

Each time we invoke Consumer::accept, it accumulates the elements in the buffer and passes them to the stream pipeline.

3. Simple Implementation Example

Let’s consider a list of integers to do the following operation:

List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5);
double percentage = .01;
List<Double> evenDoubles = integers.stream()
  .<Double>mapMulti((integer, consumer) -> {
    if (integer % 2 == 0) {
        consumer.accept((double) integer * ( 1 + percentage));
    }
  })
  .collect(toList());

In our lambda implementation of BiConsumer<T, Consumer<R>> mapper, we first select only even integers, then we add to them the amount specified in percentage, cast the result into a double, and finish invoking consumer.accept.

As we saw before, the consumer is just a buffer that passes the return elements to the stream pipeline. (As a side note, notice that we have to use a type witness <Double>mapMulti for the return value because otherwise, the compiler cannot infer the right type of R in the method’s signature.)

This is either a one-to-zero or one-to-one transformation depending on whether the element is odd or even.

Notice that the if statement in the previous code sample plays the role of a Stream::filter, and casting the integer into a double, the role of a Stream::map. Hence, we could use Stream’s filter and map to achieve the same result:

List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5);
double percentage = .01;
List<Double> evenDoubles = integers.stream()
  .filter(integer -> integer % 2 == 0)
  .<Double>map(integer -> ((double) integer * ( 1 + percentage)))
  .collect(toList());

However, the mapMulti implementation is more direct since we don’t need to invoke so many stream intermediate operations.

Another advantage is that the mapMulti implementation is imperative, giving us more freedom to do element transformations.

To support int, long, and double primitive types, we have mapMultiToDouble, mapMultiToInt, and mapMultiToLong variations of mapMulti.

For example, we can use mapMultiToDouble to find the sum of the previous List of doubles:

List<Integer> integers = Arrays.asList(1, 2, 3, 4, 5);
double percentage = .01;
double sum = integers.stream()
  .mapMultiToDouble((integer, consumer) -> {
    if (integer % 2 == 0) {
        consumer.accept(integer * (1 + percentage));
    }
  })
  .sum();

4. More Realistic Example

Let’s consider a collection of Albums:

public class Album {

    private String albumName;
    private int albumCost;
    private List<Artist> artists;

    Album(String albumName, int albumCost, List<Artist> artists) {
        this.albumName = albumName;
        this.albumCost = albumCost;
        this.artists = artists;
    }
    // ...
}

Each Album has a list of Artists:

public class Artist {

    private final String name;
    private boolean associatedMajorLabels;
    private List<String> majorLabels;

    Artist(String name, boolean associatedMajorLabels, List<String> majorLabels) {
        this.name = name;
        this.associatedMajorLabels = associatedMajorLabels;
        this.majorLabels = majorLabels;
    }
    // ...
}

If we want to collect a list of artist-album name pairs, we can implement it using mapMulti:

List<Pair<String, String>> artistAlbum = albums.stream()
  .<Pair<String, String>> mapMulti((album, consumer) -> {
      for (Artist artist : album.getArtists()) {
          consumer.accept(new ImmutablePair<String, String>(artist.getName(), album.getAlbumName()));
      }
  })

For each album in the stream, we iterate over the artists, create an Apache Commons ImmutablePair of artist-album names, and invoke Consumer::accept. The implementation of mapMulti accumulates the elements accepted by the consumer and passes them to the stream pipeline.

This has the effect of a one-to-many transformation where the results are accumulated in the consumer but ultimately are flattened into a new stream. This is essentially what Stream::flatMap does so that we can achieve the same result with the following implementation:

List<Pair<String, String>> artistAlbum = albums.stream()
  .flatMap(album -> album.getArtists()
      .stream()
      .map(artist -> new ImmutablePair<String, String>(artist.getName(), album.getAlbumName())))
  .collect(toList());

We see that both methods give identical results. We’ll cover next in which cases it is more advantageous to use mapMulti.

5. When to Use mapMulti Instead of flatMap

5.1. Replacing Stream Elements with a Small Number of Elements

As stated in the Java documentation: “when replacing each stream element with a small (possibly zero) number of elements. Using this method avoids the overhead of creating a new Stream instance for every group of result elements, as required by flatMap”.

Let’s write a simple example that illustrates this scenario:

int upperCost = 9;
List<Pair<String, String>> artistAlbum = albums.stream()
  .<Pair<String, String>> mapMulti((album, consumer) -> {
    if (album.getAlbumCost() < upperCost) {
        for (Artist artist : album.getArtists()) {
            consumer.accept(new ImmutablePair<String, String>(artist.getName(), album.getAlbumName()));
      }
    }
  })

For each album, we iterate over the artists and accumulate zero or few artist-album pairs, depending on the album’s price compared with the variable upperCost.

To accomplish the same results using flatMap:

int upperCost = 9;
List<Pair<String, String>> artistAlbum = albums.stream()
  .flatMap(album -> album.getArtists()
    .stream()
    .filter(artist -> upperCost > album.getAlbumCost())
    .map(artist -> new ImmutablePair<String, String>(artist.getName(), album.getAlbumName())))
  .collect(toList());

We see that the imperative implementation of mapMulti is more performant — we don’t have to create intermediate streams with each processed element as we do with the declarative approach of flatMap.

5.2. When It’s Easier to Generate Result Elements

Let’s write in the Album class a method that passes all the artist-album pairs with their associated major labels to a consumer:

public class Album {

    //...
    public void artistAlbumPairsToMajorLabels(Consumer<Pair<String, String>> consumer) {

        for (Artist artist : artists) {
            if (artist.isAssociatedMajorLabels()) {
                String concatLabels = artist.getMajorLabels().stream().collect(Collectors.joining(","));
                consumer.accept(new ImmutablePair<>(artist.getName()+ ":" + albumName, concatLabels));
            }
        }
    }
    // ...
}

If the artist has an association with major labels, the implementation joins the labels into a comma-separated string. It then creates a pair of artist-album names with the labels and invokes Consumer::accept.

If we want to get a list of all the pairs, it’s as simple as using mapMulti with the method reference Album::artistAlbumPairsToMajorLabels:

List<Pair<String, String>> copyrightedArtistAlbum = albums.stream()
  .<Pair<String, String>> mapMulti(Album::artistAlbumPairsToMajorLabels)
  .collect(toList());

We see that, in more complex cases, we could have very sophisticated implementations of the method reference. For instance, the Java documentation gives an example using recursion.

In general, replicating the same results using flatMap will be very difficult. Therefore, we should use mapMulti in cases where generating result elements is much easier than returning them in the form of a Stream as required in flatMap.

6. Conclusion

In this tutorial, we’ve covered how to implement mapMulti with different examples. We’ve seen how it compares with flatMap and when it’s more advantageous to use.

In particular, it’s recommended to use mapMulti when a few stream elements need to be replaced or when it’s easier to use an imperative approach to generate the elements of the stream pipeline.

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.

Partner – Microsoft – NPI EA (cat = Baeldung)
announcement - icon

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, visit the documentation page.

You can also ask questions and leave feedback on the Azure Container Apps GitHub page.

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

Azure Container Apps is a fully managed serverless container service that enables you to build and deploy modern, cloud-native Java applications and microservices at scale. It offers a simplified developer experience while providing the flexibility and portability of containers.

Of course, Azure Container Apps has really solid support for our ecosystem, from a number of build options, managed Java components, native metrics, dynamic logger, and quite a bit more.

To learn more about Java features on Azure Container Apps, visit the documentation page.

You can also ask questions and leave feedback on the Azure Container Apps GitHub page.

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

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

Partner – Orkes – NPI EA (tag = Microservices)
announcement - icon

Modern software architecture is often broken. Slow delivery leads to missed opportunities, innovation is stalled due to architectural complexities, and engineering resources are exceedingly expensive.

Orkes is the leading workflow orchestration platform built to enable teams to transform the way they develop, connect, and deploy applications, microservices, AI agents, and more.

With Orkes Conductor managed through Orkes Cloud, developers can focus on building mission critical applications without worrying about infrastructure maintenance to meet goals and, simply put, taking new products live faster and reducing total cost of ownership.

Try a 14-Day Free Trial of Orkes Conductor today.

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

Partner – MongoDB – NPI EA (tag=MongoDB)
announcement - icon

Traditional keyword-based search methods rely on exact word matches, often leading to irrelevant results depending on the user's phrasing.

By comparison, using a vector store allows us to represent the data as vector embeddings, based on meaningful relationships. We can then compare the meaning of the user’s query to the stored content, and retrieve more relevant, context-aware results.

Explore how to build an intelligent chatbot using MongoDB Atlas, Langchain4j and Spring Boot:

>> Building an AI Chatbot in Java With Langchain4j and MongoDB Atlas

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

eBook – Java Streams – NPI (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 – 3 (cat = Jackson)