Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a Map from a List with and inner list using Kotlin

Tags:

kotlin

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?

like image 271
lawkai Avatar asked Apr 25 '17 14:04

lawkai


1 Answers

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 -> ... } }

like image 132
hotkey Avatar answered Oct 17 '22 00:10

hotkey