Java Top

Finally announcing my next course. The intro price of the upcoming “Learn Spring” course will permanently increase by $50 on Friday:

>> HAVE A LOOK

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.

Secondly, 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>27.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 tutorial, 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.

Java bottom

Finally announcing my next course. The intro price of the upcoming “Learn Spring” course will permanently increase by $50 on Friday:

>> HAVE A LOOK

Leave a Reply

avatar
  Subscribe  
Notify of