This post will discuss how to convert a Map to a String in Java.

1. Using toString() method

A simple approach is to get the string representation of the map using the toString() method. The string representation of a map consists of a list of key-value pairs enclosed within curly braces, where the adjacent pairs are delimited by a comma followed by a single space and each key-value pair is separated by the equals sign (=). i.e., {K1=V1, K2=V2, ..., Kn=Vn}.

Following is a simple example demonstrating the string representation of the map:

Download  Run Code

Output:

{Java=1995, C++=1980, Ruby=1991}

2. Using Guava

Guava’s Joiner class is designed to customize the string representation of an object. Just create a joiner, and configure the separator, and specify the collection to be added.

The following code demonstrates it:

Download Code

Output:

Java:1995|C++:1980|Ruby:1991

3. Using Stream API

With Java 8 and above, you can get the string representation of a map using a Stream API, easily customized according to your needs.

Download  Run Code

Output:

Java:1995|C++:1980|Ruby:1991

That’s all about converting a Map to a String in Java.