I have a list of valid ids in a complex class (in my example a Pair).
I have a separate list of ids.
What's the best way of filtering the lists of ids to only contain ids that are present in the first case ? I'm using map to convert the list of pairs to a list of ids and then using contains in the example below. Is there a better way ?
Copy code
@Test
fun `test filter`() {
val cars = listOf("1" to "Jag","2" to "Mini")
val ids = listOf("1","2","3")
val validIds = ids.filter { cars.map { it.first }.contains(it) }
validIds `should equal` listOf("1","2")
}
b
Bornyls Deen
05/27/2020, 10:39 AM
You could use
any
to avoid having to create a new list of car ids with every iteration
Copy code
ids.filter { id -> cars.any { it.first == id } }
p
Paul N
05/27/2020, 11:07 AM
thanks, I haven't used any before, will look that up.
👍 1
a
araqnid
05/27/2020, 11:35 AM
if the list of cars was big, pulling out the keys/first values into a Set might be worthwhile
👍 2
b
Bornyls Deen
05/27/2020, 11:36 AM
I was thinking the same but wasn't 100% sure on the performance benefits.
something like this maybe
Copy code
val cars = listOf("1" to "Jag", "2" to "Mini")
val carIds = cars
.map { car -> car.first }
.toSet()
val ids = listOf("1", "2", "3")
val validIds = ids.filter { id -> carIds.contains(id) }