Kotlin List joinToString()
Syntax & Examples


Syntax of List.joinToString()

The syntax of List.joinToString() extension function is:

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

This joinToString() extension function of List creates a string from all the elements separated using separator and using the given prefix and postfix if supplied.



✐ Examples

1 Example

In this example,

  • We create a list named list1 containing strings 'apple', 'banana', 'orange'.
  • We use the joinToString function to concatenate elements of list1 into a single string.
  • We set the separator as , , prefix as [, and postfix as ].
  • The resulting string is assigned to the variable result.
  • Finally, we print the value of result to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val list1 = listOf("apple", "banana", "orange");
    val result = list1.joinToString(separator = ", ", prefix = "[", postfix = "]");
    println(result);
}

Output

[apple, banana, orange]

2 Example

In this example,

  • We create a list named list1 containing characters 'a', 'b', 'c'.
  • We use the joinToString function to concatenate elements of list1 into a single string.
  • We set the separator as -.
  • The resulting string is assigned to the variable result.
  • Finally, we print the value of result to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val list1 = listOf('a', 'b', 'c');
    val result = list1.joinToString(separator = "-");
    println(result);
}

Output

a-b-c

3 Example

In this example,

  • We create a list named list1 containing integers 10, 20, 30.
  • We use the joinToString function to concatenate elements of list1 into a single string.
  • We set the separator as , prefix as Numbers: , and postfix as !.
  • The resulting string is assigned to the variable result.
  • Finally, we print the value of result to standard output.

Kotlin Program

fun main(args: Array<String>) {
    val list1 = listOf(10, 20, 30);
    val result = list1.joinToString(separator = " ", prefix = "Numbers: ", postfix = "!");
    println(result);
}

Output

Numbers: 10 20 30!

Summary

In this Kotlin tutorial, we learned about joinToString() extension function of List: the syntax and few working examples with output and detailed explanation for each example.