Saturday, 26 February 2022

String concatenation using listOfNotNull & joinToString - Kotlin

data class User(val fName: String?, val mName: String?, val lName: String?)
val users = listOf(
        User("Ragavan", null, "V.S."),
        User("Rajeev", "Anbu", "Devan"),
        User("Ravinder", null, null),
        User("", "", ""),
        User(null, null, null)
    )
users.map {
        listOfNotNull(it.fName, it.mName, it.lName)
        .joinToString(" ").trim().takeIf { it.isNotEmpty() } ?: "NA"
}.forEach(::println)

Output:

[Ragavan V.S., Rajeev Anbu Devan, Ravinder, NA, NA]

In the above example here we are using the listOfNotNull method which implicitly handles the null check and ignore the same, then we are easy to concatenate the data using joinToString(...) method.