Best Way to Convert ArrayList to String in Kotlin

前端 未结 2 1790
天涯浪人
天涯浪人 2021-02-18 13:26

I have an ArrayList of String in kotlin

private val list = ArrayList()

I want to convert it into String with a separ

2条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-18 13:38

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

提交回复
热议问题