https://kotlinlang.org logo
Title
s

suhas

09/11/2021, 3:14 AM
Best way to filter a list using other list? I want to filter a list of objects with list of ids. As of now, I am just doing this
ids.forEach { id ->
   val person = persons.find { it.id == id}
   filteredList.add(person)
}
r

Rajkumar Singh

09/11/2021, 3:27 AM
filteredList += persons.filter { it.id in ids} OR persons.filterTo(filteredList) { it.id in ids }
👍 1
s

suhas

09/11/2021, 3:29 AM
Thanks. @Rajkumar Singh
e

ephemient

09/11/2021, 3:38 AM
if you have a mutable collection, it can be filtered in-place
persons.retainAll { it.id in ids }
👍 1
note that both these operations are O(
persons.size
·
ids.size
); if
persons
is not small then it would be better to convert
ids
to a
Set
first
💯 3
s

suhas

09/11/2021, 5:44 AM
hmm. Thanks.