Home > database >  How to make efficient list from particular object in kotlin
How to make efficient list from particular object in kotlin

Time:06-02

Hey I have list of object in which I want to combine title property value into list of object. I did this successfully without any problem. My main questions is there any better approach to do in kotlin which helps in efficient, better memory management and everything when eventList is bigger in size.

CombineList.kt

fun main() {
    val newList = mutableListOf<String>()
    val eventList = createData()
    eventList.forEachIndexed { _, event ->
        val title = event.title
        if (!title.isNullOrEmpty()) {
            newList.add(title)
        }
    }
    println(newList)
}

data class Event(val title: String? = null, val status: String? = null)

fun createData() = listOf(
    Event("text 1", "abc"),
    Event("text 2", "abc"),
    Event("text 3", "abc"),
    Event("text 4", "abc"),
    Event("", "abc"),
    Event(null, "abc")
)

CodePudding user response:

Instead of creating a new list and iteratively add each element in a forEach, you can use map which yields a new list with all the results of mapping the given function to each element:

val newList = eventList.map { it.title }.filterNot { it.isNullOrEmpty() }

The filterNot works in a similar way, giving you a list of all elements in a list, that do not fulfill a given predicate.

An overview of common operations for collections can be found here.

CodePudding user response:

Instead of creating a list of all titles with map and then filter out null and empty values it might be better to create the list with mapNotNull (and to convert empty strings to null in its lambda):

val newList = createData().mapNotNull { it.title?.ifEmpty { null } }
  • Related