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 Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
  1. DZone
  2. Data Engineering
  3. Data
  4. Two Ways to Convert Java Map to String

Two Ways to Convert Java Map to String

Vineet Manohar user avatar by
Vineet Manohar
·
May. 08, 10 · Interview
Like (0)
Save
Tweet
Share
134.40K 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.

Popular on DZone

  • gRPC on the Client Side
  • Unlocking the Power of Elasticsearch: A Comprehensive Guide to Complex Search Use Cases
  • Real-Time Analytics for IoT
  • Building a Real-Time App With Spring Boot, Cassandra, Pulsar, React, and Hilla

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: