1. Introduction

In Kotlin, a Map is a collection that contains key-value pairs of objects. Many times, we developers grapple with the need to convert a Map into a String for different reasons, such as producing outputs, further processing of data, etc.

In this article, we’ll explore various ways we can convert a Map to a String in Kotlin.

2. Different Ways of Converting a Map to String in Kotlin

Now, let’s dive into the various ways of converting a Map to a String.

Throughout this section, we’re going to use the User data class for items in our Maps.

data class User(var firstName: String, var lastName: String)

2.1. Using toString()

A classical approach uses the toString() function on the Map object. This is the default method that Kotlin provides to obtain a String representation of different types of objects. The resulting String will consist of a list of key-value pairs enclosed with the curly braces, with adjacent entries delimited by a comma followed by a single space. Each key-value pair is separated with the equals sign:

fun `using toString function`(){
    val map = mapOf<Int, User>(
      1 to User("Flore", "P"),
      2 to User("Nappy", "Sean"),
      3 to User("Ndole", "Paul"),
    )

    assertEquals(
        "{1=User(firstName=Flore, lastName=P), 2=User(firstName=Nappy, lastName=Sean), 3=User(firstName=Ndole, lastName=Paul)}", 
        map.toString()
    )
}

2.2. Using StringBuilder

In this approach, we are going to iterate over our Map, and for each iteration, we’ll concatenate the key-value pairs into a String:

@Test
fun `using string builder method`(){
    val map = mapOf<Int, User>(
      1 to User("Flore", "P"),
      2 to User("Nappy", "Sean"),
      3 to User("Ndole", "Paul"),
    )

    val sb = StringBuilder()
    map.forEach { entry ->
        sb.append("${entry.key}=${entry.value} ")
    }
    assertEquals(
        "1=User(firstName=Flore, lastName=P) 2=User(firstName=Nappy, lastName=Sean) 3=User(firstName=Ndole, lastName=Paul) ", 
        sb.toString()
    )
}

2.3. Using joinToString() Function

Another straightforward solution to joining Map elements into a String involves using the joinToString() function with a specified delimiter string, as demonstrated below:

fun `using joinToString function`(){
    val map = mapOf<Int, User>(
      1 to User("Flore", "P"),
      2 to User("Nappy", "Sean"),
      3 to User("Ndole", "Paul"),
    )

    assertEquals(
        "1=User(firstName=Flore, lastName=P), 2=User(firstName=Nappy, lastName=Sean), 3=User(firstName=Ndole, lastName=Paul)",
        map.entries.joinToString()
    )
    assertEquals(
        "1=User(firstName=Flore, lastName=P)_2=User(firstName=Nappy, lastName=Sean)_3=User(firstName=Ndole, lastName=Paul)", 
        map.entries.joinToString("_")
    )
}

What’s more, this method also permits us to configure the joinToString() function, and as a result, we can have a more customized output:

val map = mapOf<Int, User>(
  1 to User("Flore", "P"),
  2 to User("Nappy", "Sean"),
  3 to User("Ndole", "Paul"),
)

val str = map.entries.joinToString(
  prefix = "[",
  separator = ", ",
  postfix = "]",
  limit = 2,
  truncated = "..."
)
assertEquals(
    "[1=User(firstName=Flore, lastName=P), 2=User(firstName=Nappy, lastName=Sean), ...]",
    str
)

3. Converting to a JSON String

Another equally important approach to solving this problem entails that we make use of JSON as a means to convert our Map to a String.

In this section, we are certainly going to discuss two other approaches.

3.1. Conversion Using JSONObject API

Converting our Map into a JSON object before getting its String representation is another interesting way of converting a Map into a String. We’ll use JsonObject from org.json:jsonDoing our conversion this way will create a basic JSON object, where the Map entries are directly translated to the key-value pairs of a JSON object:

fun `converting to JSON first`(){
    val map = mapOf<Int, User>(
      1 to User("Flore", "P"),
      2 to User("Nappy", "Sean"),
      3 to User("Ndole", "Paul"),
    )

    val str = JSONObject(map).toString()
    assertEquals(
        """{"1":{"firstName":"Flore","lastName":"P"},"2":{"firstName":"Nappy","lastName":"Sean"},"3":{"firstName":"Ndole","lastName":"Paul"}}""",
        str
    )
}

3.2. Conversion Using Gson

Another option is using the Gson API to convert the Map into a JSON string.

We’ll use the Gson library to serialize our Map object to JSON with the toJson() method. Like every other library or dependency, we need to configure our project to include Gson.

For use with Gradle, we apply the Gson dependency in the build.gradle file:

dependencies {
  implementation 'com.google.code.gson:gson:2.10.1'
}

With Maven, add the following to the pom.xml file of the project:

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.10.1</version>
</dependency>

Since our project now includes Gson, we can now look at the conversion process. First, we’ll pass our Map object to the toJson() function as a parameter and then invoke this function on a Gson object. Finally, we call the toString() function on the JSON to get its string representation:

val map = mapOf<Int, User>(
  1 to User("Flore", "P"),
  2 to User("Nappy", "Sean"),
  3 to User("Ndole", "Paul"),
)
val str1 = Gson().toJson(map).toString()

assertEquals(
    """{"1":{"firstName":"Flore","lastName":"P"},"2":{"firstName":"Nappy","lastName":"Sean"},"3":{"firstName":"Ndole","lastName":"Paul"}}""",
    str1
)

4. Conclusion

To sum up, we’ve explored different ways we can convert a Map to a String in Kotlin.

We looked at native solutions to get Strings from Maps, such as toString() and joinToString(), and we also explored creating JSON Strings from Maps using some popular libraries. It is important to mention that the methods discussed in this article are not exhaustive. Other ways to solve this problem may exist.

As always, the code samples and relevant test cases pertaining to this article can be found over on GitHub.

Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.