Merge elements of a Collection separated by a delimiter in Kotlin
This article explores different ways to construct a new string from elements of a collection separated by the specified delimiter in Kotlin.
1. Using StringBuilder class
The idea is to iterate over the given collection and build a string out of each encountered element separated with the delimiter using a StringBuilder.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
fun mergeElements(collection: Collection<String>, separator: String): String { val sb = StringBuilder() collection.map { sb.append(it).append(separator) } return sb.removeSuffix(separator).toString() } fun main() { val collection: Collection<String> = listOf("I", "love", "Kotlin") val separator = "-"; val str = mergeElements(collection, separator) println(str) // Kotlin-Rocks } |
2. Using StringJoiner class
Alternatively, you can use the StringJoiner class, whose constructor accepts a separator. To append elements to it, you can use the add() function.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
fun mergeElements(collection: Collection<String>, separator: String): String { val sj = java.util.StringJoiner(separator) collection.map { sj.add(it) } return sj.toString() } fun main() { val collection: Collection<String> = listOf("Kotlin", "Rocks") val separator = "-"; val str = mergeElements(collection, separator) println(str) // Kotlin-Rocks } |
3. Using String.join() function
Another plausible way is to use the join() function provided by the StringJoiner class, which takes a delimiter and joins elements of the specified collection together with it.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
fun mergeElements(collection: Collection<String>, separator: String): String { return java.lang.String.join(separator, collection) } fun main() { val collection: Collection<String> = listOf("Kotlin", "Rocks") val separator = "-"; val str = mergeElements(collection, separator) println(str) // Kotlin-Rocks } |
That’s all about merging elements of a Collection separated by a delimiter 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 :)