DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • A Complete Guide on How to Convert InputStream to String In Java
  • How to Convert Files to Thumbnail Images in Java
  • Understanding Floating-Point Precision Issues in Java
  • The Long Road to Java Virtual Threads

Trending

  • Architecting an Embedded Efficiency Layer: A Platform Deep Dive into Day-Two Operational Tuning
  • Slopsquatting: Building a Scanner That Catches AI-Hallucinated Packages Before They Reach Production
  • AI-Driven Integration in Large-Scale Agile Environments
  • Setting Up Claude Code With Ollama: A Guide
  1. DZone
  2. Data Engineering
  3. Data
  4. Two Ways to Convert Java Map to String

Two Ways to Convert Java Map to String

By 
Vineet Manohar user avatar
Vineet Manohar
·
May. 08, 10 · Interview
Likes (0)
Comment
Save
Tweet
Share
139.0K Views

Join the DZone community and get the full member experience.

Join For Free

This article shows 2 ways to convert Java Map to String.

  • Approach 1: simple, lightweight – produces query string like output, but restrictive.
  • Approach 2: uses Java XML bean serialization, more robust but produces overly verbose output.

Approach 1: Map to query string format

Approach 1 converts a map to a query-string like output. Here’s what an output looks like:

name1=value1&name2=value2  

Full Code: 

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

public class MapUtil {
public static String mapToString(Map<String, String> map) {
StringBuilder stringBuilder = new StringBuilder();

for (String key : map.keySet()) {
if (stringBuilder.length() > 0) {
stringBuilder.append("&");
}
String value = map.get(key);
try {
stringBuilder.append((key != null ? URLEncoder.encode(key, "UTF-8") : ""));
stringBuilder.append("=");
stringBuilder.append(value != null ? URLEncoder.encode(value, "UTF-8") : "");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("This method requires UTF-8 encoding support", e);
}
}

return stringBuilder.toString();
}

public static Map<String, String> stringToMap(String input) {
Map<String, String> map = new HashMap<String, String>();

String[] nameValuePairs = input.split("&");
for (String nameValuePair : nameValuePairs) {
String[] nameValue = nameValuePair.split("=");
try {
map.put(URLDecoder.decode(nameValue[0], "UTF-8"), nameValue.length > 1 ? URLDecoder.decode(
nameValue[1], "UTF-8") : "");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException("This method requires UTF-8 encoding support", e);
}
}

return map;
}
}

Example usage code 

 Map<String, String> map = new HashMap<String, String>();
map.put("color", "red");
map.put("symbols", "{,=&*?}");
map.put("empty", "");
String output = MapUtil.mapToString(map);
Map<String, String> parsedMap = MapUtil.stringToMap(output);
for (String key : map.keySet()) {
Assert.assertEquals(parsedMap.get(key), map.get(key));
}

Output with Approach 1:

 symbols=%7B%2C%3D%26*%3F%7D&color=red∅=  

Caveat

  • Only supports String keys and values.
  • Due to the nature of serialization, null keys and values are not supported. Null will be converted to an empty String. This is because there is no way to distinguish between a null and an empty String in the serialized form. If you need support for null keys and values, use java.beans.XMLEncoder as shown below.

Approach 2: Java Bean XMLEncoder: Map to String

Java provides XMLEncoder and XMLDecoder classes as part of the java.beans package as a standard way to serialize and deserialize objects. This

 Map<String, String> map = new HashMap<String, String>();
map.put("color", "red");
map.put("symbols", "{,=&*?}");
map.put("empty", "");
ByteArrayOutputStream bos = new ByteArrayOutputStream();
XMLEncoder xmlEncoder = new XMLEncoder(bos);
xmlEncoder.writeObject(map);
xmlEncoder.flush();

String serializedMap = bos.toString()
System.output.println(serializedMap);

Output with Approach 2

The serialized value is shown below. As you can see this is more verbose, but can accommodate different data types and null keys and values.

<?xml version="1.0" encoding="UTF-8"?>
<java version="1.5.0_17">
<object>
<void method="put">
<string>symbols</string>
<string>{,=&*?}</string>
</void>
<void method="put">
<string>color</string>
<string>red</string>
</void>
<void method="put">
<string>empty</string>
<string></string>
</void>
</object>

 

<?xml version="1.0" encoding="UTF-8"?>
<java version="1.5.0_17">
 <object>
  <void method="put">
   <string>symbols</string>
   <string>{,=&amp;*?}</string>
  </void>
  <void method="put">
   <string>color</string>
   <string>red</string>
  </void>
  <void method="put">
   <string>empty</string>
   <string></string>
  </void>
 </object>

Java Bean XMLDecoder: String to Map


 XMLDecoder xmlDecoder = new XMLDecoder(new ByteArrayInputStream(serializedMap.getBytes()));
Map<String, String> parsedMap = (Map<String, String>) xmlDecoder.readObject();

for (String key : map.keySet()) {
Assert.assertEquals(parsedMap.get(key), map.get(key));
}

Summary

While Java provides a standard (and overly verbose) way to serialize and deserialize objects, this articles discusses an alternative lightweight way to convert a Java Map to String and back. If you are serializing a map with non-null String keys and values, then you should be able to use this alternative way, otherwise use the Java bean serialization.

 

 

From http://www.vineetmanohar.com/2010/05/07/2-ways-to-convert-java-map-to-string

Strings Data Types Java (programming language) Convert (command)

Opinions expressed by DZone contributors are their own.

Related

  • A Complete Guide on How to Convert InputStream to String In Java
  • How to Convert Files to Thumbnail Images in Java
  • Understanding Floating-Point Precision Issues in Java
  • The Long Road to Java Virtual Threads

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook