Marijan
Marijan

Reputation: 731

How to group objects by values

I have an object that looks like this:

data class Product(val name: String,
                   val maker: List<String>)

Currently, the response that I receive from the backend (and it can't be changed) is as follows:

[{"name":"Car", "maker":["Audi"]},
 {"name":"Car", "maker":["BMW"]},
 {"name":"Motorcycle", "maker":["Yamaha"]},
 {"name":"Motorcycle", "maker":["Kawasaki"]}
]

The actual list consists of a lot of data, but the name field can be trusted to be grouped by. What would be a way for me to map this data so that the end result is something like this:

[{"name":"Car", "maker":["Audi", "BMW"]},
 {"name":"Motorcycle", "maker":["Yamaha","Kawasaki"]}
]

Upvotes: 6

Views: 5997

Answers (1)

hotkey
hotkey

Reputation: 147901

Just use groupBy { ... } and then process the groups map entries, replacing them with a single Product:

val result = products.groupBy { it.name }.entries.map { (name, group) ->
    Product(name, group.flatMap { it.maker })
}

Upvotes: 12

Related Questions