Best way to filter a list using other list? I want...
# getting-started
s
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
Copy code
ids.forEach { id ->
   val person = persons.find { it.id == id}
   filteredList.add(person)
}
r
Copy code
filteredList += persons.filter { it.id in ids} OR persons.filterTo(filteredList) { it.id in ids }
👍 1
s
Thanks. @Rajkumar Singh
e
if you have a mutable collection, it can be filtered in-place
Copy code
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
hmm. Thanks.