Kotlin List - joinToString() Function



The Kotlin List joinToString() function is used to create a single string from a collection or a list by concatenating its element using a separator and using the given prefix and postfix if supplied.

By using the joinToString we can customize the delimiter such as prefix, suffix, and format of the resulting string.

There are following use cases of the joinToString() function −

  • Formatting a List for Display
  • Generating queries like SQL
  • Debugging Collections

Syntax

Following is the syntax of Kotlin list joinToString() function −

list.joinToString(
   separator: String = ", ",
   prefix: String = "",
   postfix: String = "",
   limit: Int = -1,
   truncated: String = "...",
   transform: ((T) -> CharSequence)? = null
): String

Parameters

Following are the parameters of this function −

  • separator: The string used to separate elements, default is ","
  • prefix: The string added before all the elements, default is ""
  • postfix: The string added before all the elements, default is ""
  • limit: Maximum number of elements to include in the result, default all elements are included.
  • truncated: The string representing omitted elements when the limit is reached, defaults to "..."
  • transform: A lambda function is applied to each element to format it before joining.

Return value

This function returns a string after concatenating elements of the collection.

Example 1: Basic Usages

Let's see a basic example of thejoinToString()function, which returns a string after concatenating all numbers of list −

fun main(args: Array<String>) {
   val numbers = listOf(1, 2, 3, 4, 5)
   val string = numbers.joinToString()
   println("This is String: ${string}")
}

Output

Following is the output −

This is String: 1, 2, 3, 4, 5

Example 2: Custom Separator, Prefix, and Suffix

In the following example, we use joinToString()to create a single string, concatenating elements from the list using a custom separator, prefix, and postfix −

fun main(args: Array<String>) {
   val numbers = listOf('A', 'M', 'A', 'N')
   val result = numbers.joinToString(separator = " | ", prefix = "[", postfix = "]")
   println(result)
}

Output

Following is the output −

[A | M | A | N]

Example 3: Limiting the Number of Element

Here is another example of the joinToString() function, which limits the number of elements displayed after joining them into a string −

fun main(args: Array<String>) {
   val list = listOf("Aman", "Kumar", "Gupta", "tutorialspoint")
   val string = list.joinToString(limit=3)
   println(string)
}

Output

Following is the output −

Aman, Kumar, Gupta, ...
kotlin_lists.htm
Advertisements