简体   繁体   中英

How to filter a list by using the ids of another list?

I have a list of ids . I want to filter my list and only keep the values in that list that match the id.

fun filterHelper(ids: List<Int>, list: List<People>) {
     list.filter { ids.contains(it.id) }
}

But this is very inefficient. It is essentially traversing the list O(n^2). Does Kotlin let me do better?

I asked a similar question about slicing maps recently. The answer is that there is no good built-in function, but you can work around by using a Set instead of a List for your ids, which gets you O(1) lookup time for the comparisons, so O(n) in total.

data class People(val id: Int)

fun main() {
    val people = listOf(People(1), People(2), People(3), People(4))
    val ids = setOf(2, 4)

    val filtered = people.filter { it.id in ids }
    println(filtered)
}

Output:

[People(id=2), People(id=4)]

It's worth mentioning that if you already have a list, you can easily convert to a set with:

list.toSet()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM