Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to group objects by values

Tags:

kotlin

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"]}
]
like image 944
Marijan Avatar asked Dec 18 '22 23:12

Marijan


1 Answers

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 })
}
like image 116
hotkey Avatar answered Dec 26 '22 14:12

hotkey