Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

kotlin

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?

like image 368
J_Strauton Avatar asked Nov 29 '25 03:11

J_Strauton


1 Answers

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()
like image 171
Adam Millerchip Avatar answered Dec 01 '25 02:12

Adam Millerchip