Best Way to Convert ArrayList to String in Kotlin
Solution 1
Kotlin has joinToString
method just for this
list.joinToString()
You can change a separator like this
list.joinToString(separator = ":")
If you want to customize it more, these are all parameters you can use in this function
val list = listOf("one", "two", "three", "four", "five")
println(
list.joinToString(
prefix = "[",
separator = ":",
postfix = "]",
limit = 3,
truncated = "...",
transform = { it.uppercase() }
)
)
which outputs
[ONE:TWO:THREE:...]
Solution 2
Kotlin as well has method for that, its called joinToString
.
You can simply call it like this:
list.joinToString());
Because by default it uses comma as separator but you can also pass your own separator as parameter, this method takes quite a few parameters aside from separator, which allow to do a lot of formatting, like prefix, postfix and more.
You can read all about it here
Asad Ali Choudhry
I have more than 5 years of experience in creating complex native mobile applications for iPhone and Android. I am adept in analyzing information, requirements, and system needs, evaluating end-user requirements, and developing solutions according to the needs. I am working in Dubai for the last 1.5 years and got diverse experience in development and team-leading. I can also work independently and can manage complex and big projects. I am also the co-founder of the website https://handyopinion.com/ where we share complex coding solutions with the young developers.
Updated on July 09, 2022Comments
-
Asad Ali Choudhry almost 2 years
I have an ArrayList of String in kotlin
private val list = ArrayList<String>()
I want to convert it into
String
with a separator ",". I know we can do it programatically through loop but in other languages we have mapping functions available like in java we haveStringUtils.join(list);
And in Swift we have
array.joined(separator:",");
Is there any method available to convert
ArrayList
toString
with a separator in Kotlin?And what about for adding custom separator like "-" etc?
-
Asad Ali Choudhry almost 5 yearswhat about adding own separator?
-
Asad Ali Choudhry almost 5 yearswhat about adding own separator?
-
etomun almost 3 yearsHi, can anyone help me out. When my arraylist size is one, joinToString produce ","?
-
Mohammad Sommakia over 2 yearsYou can for sure joinToString(separator: CharSequence = ", ", prefix: CharSequence = "", postfix: CharSequence = "", limit: Int = -1, truncated: CharSequence = "...", transform: ((T) -> CharSequence)? = null)