How can I succesfully do something like this?
trips.groupBy { Passenger::name if Passenger in it.passengers}
I want to reorder the List<Trips>
which has a List<Passengers>
to be [PassengerA: List<Trips>, PassengerB:...]
CodePudding user response:
If I understood your question correctly, this could be a way to do what you want:
val passengersToTrips = trips
.flatMap { trip ->
// Associate every passenger in a trip to the trip: this results in a List<Pair<Passenger, Trip>>
trip.passengers.map { passenger -> passenger to trip }
}
.groupBy(
// Group using the passenger as key (use passenger.name in case the name should be the key)
keySelector = { (passenger, _) -> passenger },
// Extracting only the trip from the pair to transform from List<Pair<Passenger, Trip> into List<Trip>
valueTransform = { (_, trip) -> trip }
)