J_Strauton
J_Strauton

Reputation: 2418

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?

Upvotes: 3

Views: 1278

Answers (1)

Adam Millerchip
Adam Millerchip

Reputation: 23147

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

Upvotes: 6

Related Questions