flatmap a list of keys and sets into a list of pairs

Viewed 465

I'm doing an online course and misread a question (which is why I think it's okay to post this question as the answer isn't anything to do with what was asked on the course!).

data class Trip(
        val driver: Driver,
        val passengers: Set<Passenger>,
        ...
)

val trips: List<Trip>

so it would end up something like

[
    driver1 : passenger1
    driver1 : passenger2
    driver2 : passenger1
    driver2 : passenger3
...
]

What I want to do is to create a list of all instances of driver and passenger, probably as pairs and I just can't think how to do it.

trips.map {t -> Pair (t.driver, t.passengers)} 

gets me some what there but obviously leaves me with the set of passengers rather than the driver:passenger pairs unpacked. II can't get the syntax for a flatmap so

 trips.flatMap {t -> Pair (t.driver, t.passengers)} 

complains that the Pair isn't iterable which I understand but I can't grasp how I would unpack the set and maintain the individual link to the driver ?

(the actual question I noticed when composing this question gives you an individual driver to find the passengers for which makes it quite a bit easier and I've done this...)

1 Answers

So for every trip you want every combination of driver/passenger, and then you want a list of all these? If so, would this do?

trips.flatMap { trip -> 
    trip.passengers.map { passenger -> 
        Pair(trip.driver, passenger) 
    } 
}

That gives you a List<Pair<Driver, Passenger>>, if that's what you're looking for? It will potentially contain duplicates, so you might want to handle that in some way.

Related