Best Way to Convert ArrayList to String in Kotlin

|▌冷眼眸甩不掉的悲伤 提交于 2020-05-27 02:46:25

问题


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?


回答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.toUpperCase() })
)

which outputs

[ONE:TWO:THREE:...]




回答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



来源:https://stackoverflow.com/questions/56515172/best-way-to-convert-arraylist-to-string-in-kotlin

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!