0

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")
)

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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 } }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.