joinToString

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

Creates a string from all the elements separated using separator and using the given prefix and postfix if supplied.

If the collection has no elements, the result consists of only prefix followed by postfix (both are empty by default).

If the collection is huge, you can specify a non-negative value of limit, in which case only the first limit elements will be appended, followed by the truncated string (which defaults to "...").

The operation is terminal.

Since Kotlin

1.0

Samples

import kotlin.math.*
import kotlin.test.*

fun main() { 
   //sampleStart 
   val numbers = listOf(1, 2, 3, 4, 5, 6)
println(numbers.joinToString()) // 1, 2, 3, 4, 5, 6
println(numbers.joinToString(prefix = "[", postfix = "]")) // [1, 2, 3, 4, 5, 6]
println(numbers.joinToString(prefix = "<", postfix = ">", separator = "•")) // <1•2•3•4•5•6>

val chars = charArrayOf('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q')
println(chars.joinToString(limit = 5, truncated = "...!") { it.uppercaseChar().toString() }) // A, B, C, D, E, ...!

// If the receiver is empty, the result only contains prefix and postfix
println("emptyList<Int>().joinToString().isEmpty() is ${emptyList<Int>().joinToString().isEmpty()}") // true
println(emptyList<Int>().joinToString(prefix = "[", postfix = "]")) // [] 
   //sampleEnd
}