so I have a list of orders and then a list of cars...
# getting-started
o
so I have a list of orders and then a list of cars, when I get the list of cars I would like to take from it all the cars whose
id
exists in the list of orders
isn’t it
cars.filter { it.id in orders }
?
d
If
orders
is a list of car IDs - yes.
o
it is a list of objects, each has a carId
yea I thought I needed like
iterator()
or another find or something?
its basically a double for loop
m
you could flush the order.ids into a hashset to make it faster...
👍 1
d
cars.filter { car -> orders.any { order -> order.carId == car.id } }
Or as Martin says, first make a set of car ids from all orders, if this is performance critical code.
o
Ahh,
any
thank you that does it
back to my example
if I wanted to then say
car.order = order
chaining a
.map
after the filter doesn’t grant me the order, i just get the car of course
i can do it after the
.any
Ithink
nah I can’t, especially if order is val, I need to return the desired cars as
car.copy(order = neworder)
later
Copy code
for (result in listings.results) {
    for (order in orders) {
        if (result.id == order.listingId) {
            purchasedCars.add(
                result.copy(
                    order = order,
                    contactOptions = emptyList(),
                    isFavorite = true
                )
            )
        }
    }
}
this is what I’d like to do
to also act on the cars I found according to the
any
, in the same chain
d
Copy code
listings.results.flatMapTo(purchasedCars) { result ->
    orders.mapNotNull { order -> 
        if (result.id == order.listingId) {
            result.copy(...)
        } else null
    }
}
or something like that
👍🏻 1
But you should really use a map indexed by ID here so that you don't have to loop through the lists all the time