How to convert an ArrayList to String in Kotlin?



In this article, we will see how we can convert an ArrayList in Kotlin to a String. In order to do so, we will use a String function called joinToString() that is provided by the Kotlin library. Its definition goes like this −

fun <T> Array<out T>.joinToString(
   // the String will be separated by comma
   separator: CharSequence = ", ",
   
   // prefix to the String
   prefix: CharSequence = "",
   
   // postfix to the String
   postfix: CharSequence = "",
   
   // This number of elements will be printed;
   // the remaining will be denoted by truncated sequence
   limit: Int = -1,
   truncated: CharSequence = "...",
   
   // any transformation required over the String
   transform: ((T) -> CharSequence)? = null
): String

This function takes several attributes in order to convert an arrayList into a String.

Example – Converting an ArrayList to String

Now let's take a working example and convert an ArrayList to a String −

fun main(args: Array<String>) {
   val mylist = listOf("Jam", "bread", "apple", "mango")
   println("Input ArrayList: " + mylist)
   println("ArrayList to String: " +
      mylist.joinToString(
         prefix = "[",
         separator = "-",
         postfix = "]",
         truncated = "...",
         transform = { it.uppercase() }
      )
   )
}

Output

It will produce the following output −

Input ArrayList: [Jam, bread, apple, mango]
ArrayList to String: [JAM-BREAD-APPLE-MANGO]

Advertisements