Learn through the super-clean Baeldung Pro experience:
>> Membership and Baeldung Pro.
No ads, dark-mode and 6 months free of IntelliJ Idea Ultimate to start with.
Last updated: March 19, 2024
One of the most common operations in software development is to print the content of a List in some specific format.
In this tutorial, we’ll explore different techniques to print a List‘s elements separated by a comma in Kotlin.
The first technique uses the for control to iterate through the List and manually print the elements separated by commas:
val myList = listOf("apple", "banana", "cherry", "date")
var result = ""
for (item in myList) {
result += if (result.isEmpty()) item else ", $item"
}
assertEquals("apple, banana, cherry, date", result)
Kotlin provides a built-in function joinToString that makes it straightforward to concatenate the elements of a List with a separator:
val myList = listOf("apple", "banana", "cherry", "date")
val result = myList.joinToString(", ")
assertEquals("apple, banana, cherry, date", result)
In Kotlin, the reduce method is a higher-order function that is often used for combining the elements of a collection into a single result. We can take advantage of the reduce function to concatenate the elements in the List:
val myList = listOf("apple", "banana", "cherry", "date")
val result = myList.reduce { acc, s -> "$acc, $s" }
assertEquals("apple, banana, cherry, date", result)
Printing the contents of a List separated by commas in Kotlin can be achieved using various methods. The joinToString function provides a very concise and readable solution. However, using a for loop or the reduce function can be helpful in situations where we need more manual control over the process.