so I have data classes like this:
data class Item(val name: String)
data class Order(val id: Int, val items: List<Item>)
and I have a list of Orders.
my question is, how can I create a map with Item name as key and list of Orders with that item as value using Kotlin's collections API?
Given that you have orders: List<Order>
, you can first flatMap
the orders into pairs of Order
and item name (so that each Order
can occur multiple times if it has more than one Item
), and then group these pairs by the item name using groupBy
, taking the orders from the pairs into the groups:
val result = orders
.flatMap { o -> o.items.map { i -> o to i.name } }
.groupBy({ (_, name) -> name }, valueTransform = { (o, _) -> o })
In the groupBy
arguments, { (_, name) -> name }
is the grouping key selector function that takes the name from each pair, and { (o, _) -> o }
transforms the items when collecting them to the lists, it takes the order from the pair.
(runnable demo of this code)
If you want to eliminate multiple occurences of the same Order
in case it contains a single Item
multiple times, use distinct
as follows: .flatMap { o -> o.items.distinct().map { i -> ... } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With