How to create a map from a list using an internal list using 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 named Item as a key and a list of orders with this element as a value using the Kotlin collections API?

+6
source share
1 answer

Given what you have orders: List<Order>, you can first place flatMaporders for pairs Orderand the name of the element (so that each Ordercan occur several times if it has more than one Item), and then group these pairs by the name of the element, using groupBy, taking orders from pairs into groups:

val result = orders
        .flatMap { o -> o.items.map { i -> o to i.name } }
        .groupBy({ (_, name) -> name }, valueTransform = { (o, _) -> o })

groupBy { (_, name) -> name } - , , { (o, _) -> o } , .

(runnable demo )

Order, Item , distinct : .flatMap { o -> o.items.distinct().map { i -> ... } }

+4

Source: https://habr.com/ru/post/1016767/


All Articles