https://kotlinlang.org logo
#getting-started
Title
# getting-started
o

oday

05/25/2021, 2:19 PM
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

diesieben07

05/25/2021, 2:22 PM
If
orders
is a list of car IDs - yes.
o

oday

05/25/2021, 2:24 PM
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

Martin Cazares

05/25/2021, 2:26 PM
you could flush the order.ids into a hashset to make it faster...
👍 1
d

diesieben07

05/25/2021, 2:44 PM
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

oday

05/25/2021, 3:23 PM
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

diesieben07

05/27/2021, 3:29 PM
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
3 Views