How To Convert Map To String In Java

Converting a map to a string in Java is a common task that developers often have to work on within their projects. This includes converting map key-value pairs to string format so that it is easily readable and transferrable.  This conversion can be accomplished using different methods, each having its own advantages or disadvantages. In this article, we will explore some popular methods of converting Map to String in Java and compare their performance and efficiency.

Transforming maps into strings can prove advantageous for multiple purposes, like:

  • Showcasing map data on a user interface: In the realm of UI, conveying information in a clear and comprehensible manner is crucial. By converting maps into strings, we can enhance the accessibility and understanding of the data.
  • Storing Map data in a database: Many databases require data to be stored in a string format.  When working with map data, it is often necessary to convert it to a string before storing it in the database
  • Serializing/Transferring Map data over a network:  Similarly, when transferring map data over a network or serializing it to a file, it needs to be transformed into a string format for easy transmission and reconstruction at the receiving end. To simplify these processes, map data must be converted into a string format that allows for effortless transmission and reconstruction.

Different Approaches on how to convert map to string in Java

There are different ways to convert a Map to a String in Java, these are:

  1. Using the toString() method
  2. Using StringBuilder
  3. Using a JSON library like Jackson

Approach 1:  Using the toString() Method

To convert a Map into a String, this method utilizes the toString() method of the Map interface. In Java’s map interface, there’s already a pre-set implementation of the toString() method that generates a string representation of the map. This returned string is enclosed in curly braces and includes key-value pairs separated by commas.

Example:

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

public class Main {
    public static void main(String[] args) {
       Map<String, Integer> map = new HashMap<>();
       map.put("one", 1);     // input
       map.put("two", 2);     // input
String mapAsString = map.toString();
System.out.println(mapAsString); // {one=1, two=2}
    }
}

Output:

{one=1, two=2}

Explanation:

  • The toString() method of the Map interface returns a String representation of the Map.
  • The returned String is enclosed in curly braces and contains key-value pairs separated by commas.

Approach 2: UsingStringBuilder

This approach involves iterating over the Map entries and appending them to a StringBuilder object. This allows for more control over the formatting of the resulting string, and is useful when customizing the string output is important.

Example:

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

public class Main {
    public static void main(String[] args) {
      Map<String, Integer> map = new HashMap<>();
     map.put("one", 1);    // input
     map.put("two", 2);   // input

StringBuilder sb = new StringBuilder();
for (Map.Entry<String, Integer> entry : map.entrySet()) {   
 // appending each key-value pair to the StringBuilder
    sb.append(entry.getKey())      
      .append("=")
      .append(entry.getValue())
      .append(",");
}
String mapAsString = sb.toString();
System.out.println(mapAsString);    // one=1,two=2,
    }
}

Output:

one=1,two=2,

Explanation:

  • We use a StringBuilder object to build the final String representation of the Map.
  • We iterate over the Map using a for-each loop and append each key-value pair to the StringBuilder.
  • Keys and values are separated by an equal sign, and each key-value pair is separated by a comma.

Approach 3: Using Jackson Library

This method involves using a JSON library like Jackson to serialize the Map into a JSON string. This method is very flexible and powerful, and can handle more complex Map structures. However, this approach requires adding the Jackson library dependency to the project.

Example:

import org.codehaus.jackson.map.ObjectMapper;
import java.util.HashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
     ObjectMapper objectMapper = new ObjectMapper();
        Map<String, Integer> map = new HashMap<>();
        map.put("one", 1);   // input
        map.put("two", 2);   // input
            // now converting the HashMap to a JSON-formatted string
        String mapAsString = objectMapper.writeValueAsString(map); 
        System.out.println(mapAsString); // {"one":1,"two":2}
    }
}

Output:

{"one":1,"two":2}

Explanation:

  • We use the ObjectMapper class from the Jackson library to convert the Map to a JSON string.
  • First, create a new instance of the ObjectMapper class using the default constructor
  • Create a new HashMap instance with String keys and Integer values
  • Add two key-value pairs to the HashMap
  • Convert the HashMap to a JSON-formatted string using the writeValueAsString() method of the ObjectMapper class
  • Store the JSON-formatted string in a variable called mapAsString
  • Print the value of mapAsString to the console. This should output the JSON-formatted string representation of the map

Best Approach for “how to convert map to string in Java”

For converting a map to string in Java, using a JSON library like Jackson is a flexible and powerful option for the following reasons:

  • Wide range of data: Jackson supports a wide range of data structures, including Maps with nested values, making it a powerful option for handling complex Map structures.
  • Customizable: Jackson provides customizable options for serializing Map data, allowing for fine-tuned control over how the Map data is converted to a string format.
  • Well-supported: Jackson is widely used in industry and has a large community of developers contributing to its ongoing development and maintenance, providing a reliable and well-supported option for converting Map data to a string format.
  • Versatility: Jackson can handle not only basic data types but also more complex data types like objects, arrays, and collections, making it a versatile and flexible choice for Map serialization.
  • High performance: Jackson provides high performance and low overhead, making it a great choice for use in large-scale applications where efficiency and speed are important factors.

Sample Problem 1:  Using the toString() Method

An HR department needs to send employee details to an insurance provider for group health insurance enrollment. The employee details including their name and age are stored in a map. The HR department needs to convert the map to a string to send it to the insurance provider via an API.

Write a program in java to convert this map to string using the toString() Method

Input:

Map<String, Integer> peopleAge = new HashMap<>();
peopleAge.put("Alice", 25);
peopleAge.put("Bob", 30);
peopleAge.put("Charlie", 35);

Solution:

  • First, create a Stream of entries from the map using the entrySet() function.
  • Then use the map() function to convert each entry into a string of the form “name:age”
  • Finally, we use the collect() function with joining() to concatenate all the strings into a single string, separated by a comma (,)
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

public class Main {
    public static void main(String[] args) {
        Map<String, Integer> peopleAge = new HashMap<>();    // input
        peopleAge.put("Alice", 25);
        peopleAge.put("Bob", 30);
        peopleAge.put("Charlie", 35);

        String result = peopleAge.entrySet()      // creating a Stream of entries
        .stream()
        .map(entry -> entry.getKey() + ":" + entry.getValue())
        .collect(Collectors.joining(", "));    //  concatenating all the strings into a single string
        System.out.println(result);
    }
} 

Output:

Bob:30, Alice:25, Charlie:35

Sample Problem 2: Using StringBuilder

Suppose you work for a logistics company and you have a Map that contains the details of packages to be delivered. The map has the package ID and the delivery status. You need to convert this map to a string to display it on the delivery tracking portal.

Input String:

Map<String, String> packageStatusMap = new HashMap<>();
packageStatusMap.put("PKG123", "In Transit");
packageStatusMap.put("PKG456", "Out for Delivery");
packageStatusMap.put("PKG789", "Delivered");

Solution:

  • First create a StringBuilder object to store the converted map.
  • Then loop through each entry in the  Map using a for-each loop.
  • For each entry, retrieve the key and corresponding value and  append them to the StringBuilder object in the JSON format.
  • Finally, remove the trailing comma and  add the closing curly brace to complete the JSON string.
import java.util.HashMap;
import java.util.Map;
public class Main {
    public static void main(String[] args) {
        Map<String, String> packageStatusMap = new HashMap<>();   // input
        packageStatusMap.put("PKG123", "In Transit");
        packageStatusMap.put("PKG456", "Out for Delivery");
        packageStatusMap.put("PKG789", "Delivered");

        StringBuilder mapAsString = new StringBuilder("{");
        for (Map.Entry<String, String> entry : packageStatusMap.entrySet()) {
            String key = entry.getKey();
            String value = entry.getValue();
                 // appending the key and value to the StringBuilder object
            mapAsString.append("\"").append(key).append("\":\"").append(value).append("\",");
        }

         // removing the trailing comma and add the closing curly brace
        mapAsString.deleteCharAt(mapAsString.length() - 1);
        mapAsString.append("}");
        System.out.println(mapAsString);
    }
}

Output:

{"PKG123":"In Transit","PKG789":"Delivered","PKG456":"Out for Delivery"}

Sample Problem 3: Using a JSON library like Jackson

Suppose you are working on a project for a social media company, where you have a Map that contains the user ID and their respective posts. You need to convert this map to a JSON string to send it to the client-side application.

Input:

Map<Integer, List<String>> userPostsMap = new HashMap<>();
userPostsMap.put(1001, Arrays.asList("post1", "post2", "post3"));
userPostsMap.put(1002, Arrays.asList("post4", "post5"));
userPostsMap.put(1003, Arrays.asList("post6"));

Solution:

We can solve this problem using the following given approach:

  • First create an ObjectMapper object from the Jackson library, which is a powerful JSON processing library for Java
  • Then pass the Map object to the writeValueAsString method of the ObjectMapper object to convert the Map to a JSON string.
  • The Jackson library handles all the complexities involved in serializing the Map to a JSON string.
import org.codehaus.jackson.map.ObjectMapper;
import java.util.HashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
       ObjectMapper objectMapper = new ObjectMapper();
        Map<Integer, List<String>> userPostsMap = new HashMap<>();  // input
        userPostsMap.put(1001, Arrays.asList("post1", "post2", "post3"));
        userPostsMap.put(1002, Arrays.asList("post4", "post5"));
        userPostsMap.put(1003, Arrays.asList("post6"));

         // passing the Map object to the writeValueAsString method of the ObjectMapper object to  
        //  convert the Map to a JSON string
        String mapAsString = objectMapper.writeValueAsString(userPostsMap);
    System.out.println(mapAsString);
    }
}

Output:

{"1001":["post1","post2","post3"],"1002":["post4","post5"],"1003":["post6"]}

Conclusion on how to convert map to string in java

In this tutorial, we explored three different approaches to convert a Map to a String in Java.  This topic is relevant when we need to convert Map data into a String format for further processing or display purposes. If conversion of the map to a JSON string is needed, then using the Gson library is ideally the best approach. Jackson is a flexible and powerful option for converting Map to string format and provides a variety of options to handle complex data structures and support high performance and low overhead. When choosing the final approach, please consider factors like performance, ease of use, and the specific requirements of the conversion. We encourage you to try all the approaches before making a final decision.