Print contents of a List separated by comma in Kotlin
This article explores different ways to print contents of a List separated by a comma in Kotlin.
1. Using joinToString() function
The standard solution to concatenate all the list elements with a separator is with the joinToString() function.
|
1 2 3 4 5 6 7 8 |
fun main() { val list = listOf("A", "B", "C", "D") val separator = ", " val str = list.joinToString(separator) println(str) // A, B, C, D } |
The joinToString() function is overloaded to accept the prefix and postfix as well.
|
1 2 3 4 5 6 7 8 9 10 |
fun main() { val list = listOf("A", "B", "C", "D") val separator = ", " val prefix = "[" val postfix = "]" val str = list.joinToString(separator, prefix, postfix) println(str) // [A, B, C, D] } |
2. Using String.join() function
If you don’t mind using Java’s String class, you can use the String.join() function. It connects all strings in a List together with the specified separator.
|
1 2 3 4 5 6 7 8 |
fun main() { val list = listOf("A", "B", "C", "D") val separator = ", " val str = java.lang.String.join(separator, list) println(str) // A, B, C, D } |
3. Using StringJoiner class
Another Java-based solution involves using the StringJoiner class to construct a sequence of elements separated by a separator.
|
1 2 3 4 5 6 7 8 9 10 11 |
import java.util.StringJoiner fun main() { val list = listOf(1, 2, 3, 4, 5) val separator = ", " val joiner = StringJoiner(separator) list.forEach { joiner.add(it.toString()) } println(joiner.toString()) // 1, 2, 3, 4, 5 } |
To create a string beginning with the given prefix and ending with the given postfix, do like:
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import java.util.StringJoiner fun main() { val list = listOf("A", "B", "C", "D") val separator = ", " val prefix = "[" val postfix = "]" val joiner = StringJoiner(separator, prefix, postfix) list.forEach { joiner.add(it) } println(joiner.toString()) // [A, B, C, D] } |
4. Using String builder
The String builder can be used to efficiently perform multiple string manipulation operations. The following code example demonstrates the usage of String builder, to collect contents of a List separated by a comma.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
fun main() { val list = listOf("A", "B", "C", "D") val sb = StringBuilder() var separator = "" for (s in list) { sb.append(separator).append(s) separator = ", " } println(sb.toString()) // A, B, C, D } |
That’s all about printing contents of a List separated by a comma in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)