Java

How to Convert a Map to a String in Java?

In Java, a map is a set of key-value pairs, having a unique key that is mapped to a specific value. Sometimes, it is necessary to convert a map to a string representation for various reasons such as serialization, storage, or communication. The purpose of this conversion is often to display or transmit the contents of the map as a single text string.

Here are several practices for the conversion of a map to a string in Java:

Using the toString() Method

The toString() method of the Map interface provides a simple way to perform the conversion of a Map to a String. The string has a comma that is a separated list of key-value pairs wrapped by curly braces. This method gives back a string that represents the Map object.

Let’s take an example that represents how to convert a Map to a String in Java:

import java.util.HashMap;
import java.util.Map;

public class MapToStringExample {
    public static void main(String[] args) {
        Map map = new HashMap();
        map.put("apple", 1);
        map.put("banana", 2);
        map.put("orange", 3);

        String mapAsString = map.toString();
        System.out.println(mapAsString);
    }
}

The description of the code is given below:

  • In this example, create a map object called “map” and add some key-value pairs to it.
  • Then, call the toString() method on the map object and assign the resulting string to a variable called mapAsString.
  • Finally, print out the “mapAsString” variable to the console, which displays the string representation of the map object.

Output

The output of the above code shows a string that represents the Map object.

Note that the order of the elements in the string may not be the same as the order in which they were added to the map object.

Using StringBuilder and Map.forEach() Methods

This method creates a StringBuilder object and appends each key-value pair in the map. The code is mentioned below:

import java.util.HashMap;
import java.util.Map;

public class MapToStringExample {
public static void main(String[] args) {
        Map map = new HashMap();
        map.put("key1", "value1");
        map.put("key2", "value2");
        StringBuilder sb = new StringBuilder();
        sb.append("{");
        map.forEach((key, value) -> {
            sb.append(key).append("=").append(value).append(", ");
        });
        sb.setLength(sb.length() - 2);
        sb.append("}");
       
        String result = sb.toString();
        System.out.println(result);
    }
}

The explanation of the above code is enlisted below:

  • First, create a “StringBuilder” object and append each key-value pair in the map to it.
  • After that, the forEach() method is used to iterate over the map and append each key-value pair to the StringBuilder.
  • Finally, the StringBuilder is converted to a string using the toString() method.

The output shows that StringBuilder is transformed into a string through the toString() method.

Conclusion

To convert a map object to a string representation in Java, use a “StringBuilder” to accumulate the string. After that, iterate over the entries in the map, and append each key-value pair to the StringBuilder with the desired formatting. Finally, call the toString() method on the StringBuilder to convert it to the object.

This article has explained the conversion of a map to a string in Java.

About the author

Syed Minhal Abbas

I hold a master's degree in computer science and work as an academic researcher. I am eager to read about new technologies and share them with the rest of the world.