This article explores different ways to convert a Map to a String in Kotlin.

1. Using joinToString() function

The standard solution to join elements of a map with the specified delimiter is using the joinToString() function. Its usage is demonstrated below:

Download Code

Output:

United States=Dollar, European Union=Euro, United Kingdom=Pound

 
We can easily customize the output according to our needs.

Download Code

Output:

[United States=Dollar, European Union=Euro, …]

2. Converting to JSON String

We can also convert the Map into a JSON and get its string representation. The following solution uses org.json.JSONObject to construct a JSONObject from an object using its getters. Then it calls the toString() function to make a JSON string of the JSONObject.

Download Code

Output:

{"United States":"Dollar","European Union":"Euro","United Kingdom":"Pound"}

 
Alternatively, we can use the Gson library for converting an object into a JSON string. The idea is to call the toJson() function to convert an object into a JSON and invoke the toString() function to get the string representation of the JSON.

Download Code

Output:

{"United States":"Dollar","European Union":"Euro","United Kingdom":"Pound"}

3. Using toString() function

If you just need the string representation of the map, consider using the toString() function. It consists of a list of key-value pairs enclosed within the 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}. For instance,

Download Code

Output:

{United States=Dollar, European Union=Euro, United Kingdom=Pound}

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