Enterprise Java

Converting a Map to a Spring MultiValueMap

In Spring, a MultiValueMap is a structure for storing multiple values for a single key. This can be useful in scenarios such as HTTP parameters or headers where we might have multiple values for a single parameter. This article will explore the process of converting a Map to a Spring MultiValueMap using different methods.

1. What is a MultiValueMap?

A MultiValueMap is an interface provided by the Spring framework that allows a key to be associated with multiple values which is not possible with a standard Map implementation where each key is associated with a single value. The interface extends the Map<K, List<V>> interface.

2. Example Scenario

Suppose we have a Map<String, String[]> with parameters and their respective values. Our goal is to convert this Map<String, String[]> into a MultiValueMap<String, String>.

2.1 Add Spring Framework Dependency

Add the Spring framework dependency to the project. If you’re using Maven, add the following to your pom.xml:

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>6.1.10</version>
        </dependency>

3. Methods to Convert Map to MultiValueMap

3.1 Using Spring’s MultiValueMap and LinkedMultiValueMap

The LinkedMultiValueMap class from the Spring framework provides a convenient implementation of the MultiValueMap interface.

public class MapToMultiValueMapExample1 {

    public static MultiValueMap<String, String> convert(Map<String, String[]> map) {
        MultiValueMap<String, String> multiValueMap = new LinkedMultiValueMap<>();

        for (Map.Entry<String, String[]> entry : map.entrySet()) {
            multiValueMap.put(entry.getKey(), Arrays.asList(entry.getValue()));
        }

        return multiValueMap;
    }

    public static void main(String[] args) {
        Map<String, String[]> carPreferences = Map.of(
                "Toyota", new String[]{"Camry", "Corolla", "Prius"},
                "Ford", new String[]{"Mustang", "Fiesta", "Focus"},
                "BMW", new String[]{"X5", "X3", "i8"}
        );

        MultiValueMap<String, String> multiValueMap = convert(carPreferences);

        System.out.println(multiValueMap);
    }
}

The above code snippet iterates through each entry (Map.Entry<String, String[]> entry) in the input map. For each entry, it retrieves the key (entry.getKey()) and the corresponding array of strings (entry.getValue()). It converts the array of strings into a List<String> using Arrays.asList(entry.getValue()). Finally, it stores this key-value pair (entry.getKey() as the key and Arrays.asList(entry.getValue()) as the value) into the multiValueMap using the put method.

Running the main method will produce the following output:

Figure 1: Output from Java Convert Map to Spring MultiValueMap - Example 1

3.2 Using Java Streams

The Java 8 Stream API, offering a functional approach to handling collections, can be utilized to convert a Map<String, String[]> into a MultiValueMap<String, String>.

public class MapToMultiValueMapExample2 {

    public static MultiValueMap<String, String> convertUsingStreams(Map<String, String[]> map) {
        return map.entrySet().stream()
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        entry -> Arrays.asList(entry.getValue()),
                        (oldValue, newValue) -> {
                            oldValue.addAll(newValue);
                            return oldValue;
                        },
                        LinkedMultiValueMap::new
                ));
    }

    public static void main(String[] args) {
        Map<String, String[]> carPreferences = Map.of(
                "Toyota", new String[]{"Camry", "Corolla", "Prius"},
                "Ford", new String[]{"Mustang", "Fiesta", "Focus"},
                "BMW", new String[]{"X5", "X3", "i8"}
        );

        MultiValueMap<String, String> multiValueMap = convertUsingStreams(carPreferences);

        System.out.println(multiValueMap);
    }
}

In the code snippet above:

  • We use the stream method to create a stream of the map’s entries.
  • The Collectors.toMap method collects these entries into a new map.
  • Map.Entry::getKey and entry -> Arrays.asList(entry.getValue()) extract the key and convert the array to a list, respectively.
  • (oldValue, newValue) -> { oldValue.addAll(newValue); return oldValue; } merges lists in case of key collisions.
  • LinkedMultiValueMap::new creates a new instance of LinkedMultiValueMap.

Output is:

{Toyota=[Camry, Corolla, Prius], Ford=[Mustang, Fiesta, Focus], BMW=[X5, X3, i8]}

4. Conclusion

In this article, we explored various methods to convert a Map<String, String[]> to a MultiValueMap<String, String> in Java. We discussed using Spring’s LinkedMultiValueMap for straightforward implementation and leveraging Java 8’s Stream API for a functional approach.

5. Download the Source Code

This article covered how to convert a Map to a MultiValueMap in Java using the Spring framework.

Download
You can download the full source code of this example here: convert a Map to a MultiValueMap in Java using Spring

Omozegie Aziegbe

Omos Aziegbe is a technical writer and web/application developer with a BSc in Computer Science and Software Engineering from the University of Bedfordshire. Specializing in Java enterprise applications with the Jakarta EE framework, Omos also works with HTML5, CSS, and JavaScript for web development. As a freelance web developer, Omos combines technical expertise with research and writing on topics such as software engineering, programming, web application development, computer science, and technology.
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button