Expand Authors Top

If you have a few years of experience in the Java ecosystem and you’d like to share that with the community, have a look at our Contribution Guidelines.

Expanded Audience – Frontegg – Security (partner)
announcement - icon User management is very complex, when implemented properly. No surprise here.

Not having to roll all of that out manually, but instead integrating a mature, fully-fledged solution - yeah, that makes a lot of sense.
That's basically what Frontegg is - User Management for your application. It's focused on making your app scalable, secure and enjoyable for your users.
From signup to authentication, it supports simple scenarios all the way to complex and custom application logic.

Have a look:

>> Elegant User Management, Tailor-made for B2B SaaS

November Discount Launch 2022 – Top
We’re finally running a Black Friday launch. All Courses are 30% off until the end of this week:

>> GET ACCESS NOW

November Discount Launch 2022 – TEMP TOP (NPI)
We’re finally running a Black Friday launch. All Courses are 30% off until the end of this week:

>> GET ACCESS NOW

1. Overview

In this tutorial, we'll focus on conversion from a Map to a String and the other way around.

First, we'll see how to achieve these using core Java methods, and afterward, we'll use some third-party libraries.

2. Basic Map Example

In all examples, we're going to use the same Map implementation:

Map<Integer, String> wordsByKey = new HashMap<>();
wordsByKey.put(1, "one");
wordsByKey.put(2, "two");
wordsByKey.put(3, "three");
wordsByKey.put(4, "four");

3. Convert a Map to a String by Iterating

Let's iterate over all the keys in our Map and, for each of them, append the key-value combination to our resulting StringBuilder object.

For formatting purposes, we can wrap the result in curly brackets:

public String convertWithIteration(Map<Integer, ?> map) {
    StringBuilder mapAsString = new StringBuilder("{");
    for (Integer key : map.keySet()) {
        mapAsString.append(key + "=" + map.get(key) + ", ");
    }
    mapAsString.delete(mapAsString.length()-2, mapAsString.length()).append("}");
    return mapAsString.toString();
}

To check if we converted our Map correctly, let's run the following test:

@Test
public void givenMap_WhenUsingIteration_ThenResultingStringIsCorrect() {
    String mapAsString = MapToString.convertWithIteration(wordsByKey);
    Assert.assertEquals("{1=one, 2=two, 3=three, 4=four}", mapAsString);
}

4. Convert a Map to a String Using Java Streams

To perform conversion using streams, we first need to create a stream out of the available Map keys.

Second, we're mapping each key to a human-readable String.

Finally, we're joining those values, and, for the sake of convenience, we're adding some formatting rules using the Collectors.joining() method:

public String convertWithStream(Map<Integer, ?> map) {
    String mapAsString = map.keySet().stream()
      .map(key -> key + "=" + map.get(key))
      .collect(Collectors.joining(", ", "{", "}"));
    return mapAsString;
}

5. Convert a Map to a String Using Guava

Let's add Guava into our project and see how we can achieve the conversion in a single line of code:

<dependency>
    <groupId>com.google.guava</groupId>
    <artifactId>guava</artifactId>
    <version>31.0.1-jre</version>
</dependency>

To perform the conversion using Guava's Joiner class, we need to define a separator between different Map entries and a separator between keys and values:

public String convertWithGuava(Map<Integer, ?> map) {
    return Joiner.on(",").withKeyValueSeparator("=").join(map);
}

6. Convert a Map to a String Using Apache Commons

To use Apache Commons, let's add the following dependency first:

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-collections4</artifactId>
    <version>4.2</version>
</dependency>

The joining is very straightforward — we just need to call the StringUtils.join method:

public String convertWithApache(Map map) {
    return StringUtils.join(map);
}

One special mention goes to the debugPrint method available in Apache Commons. It is very useful for debugging purposes.

When we call:

MapUtils.debugPrint(System.out, "Map as String", wordsByKey);

the debug text will be written to the console:

Map as String = 
{
    1 = one java.lang.String
    2 = two java.lang.String
    3 = three java.lang.String
    4 = four java.lang.String
} java.util.HashMap

7. Convert a String to a Map Using Streams

To perform conversion from a String to a Map, let's define where to split on and how to extract keys and values:

public Map<String, String> convertWithStream(String mapAsString) {
    Map<String, String> map = Arrays.stream(mapAsString.split(","))
      .map(entry -> entry.split("="))
      .collect(Collectors.toMap(entry -> entry[0], entry -> entry[1]));
    return map;
}

8. Convert a String to a Map Using Guava

A more compact version of the above is to rely on Guava to do the splitting and conversion for us in a one-line process:

public Map<String, String> convertWithGuava(String mapAsString) {
    return Splitter.on(',').withKeyValueSeparator('=').split(mapAsString);
}

9. Conclusion

In this article, we saw how to convert a Map to a String and the other way around using both core Java methods and third-party libraries.

The implementation of all of these examples can be found over on GitHub.

November Discount Launch 2022 – Bottom
We’re finally running a Black Friday launch. All Courses are 30% off until the end of this week:

>> GET ACCESS NOW

Generic footer banner
Comments are closed on this article!