Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best Way to Convert ArrayList to String in Kotlin

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 have

StringUtils.join(list); 

And in Swift we have

array.joined(separator:","); 

Is there any method available to convert ArrayList to String with a separator in Kotlin?

And what about for adding custom separator like "-" etc?

like image 840
Asad Ali Choudhry Avatar asked Jun 09 '19 13:06

Asad Ali Choudhry


People also ask

What is Kotlin string interpolation?

String interpolation in Kotlin allows us to easily concatenate constant strings and variables to build another string elegantly.

Is Kotlin list an ArrayList?

ArrayList class is used to create a dynamic array in Kotlin. Dynamic array states that we can increase or decrease the size of an array as pre requisites. It also provide read and write functionalities.


2 Answers

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:...]

like image 66
Vladimír Bielený Avatar answered Sep 21 '22 21:09

Vladimír Bielený


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

like image 28
FilipRistic Avatar answered Sep 21 '22 21:09

FilipRistic