Hey I have huge data coming from server. I want to sort them and group them. I tried some code it's working fine. I just want to know is there any better way to optimise the code, which helps in better efficiency.
val products = ABC()
products?.sortedBy { it.category }?.groupBy { it.category }
Abc
data class Abc(
val category: String? = null,
val categoryId: String? = null,
...// more property
)
Can you guys know any better approach. Thanks
CodePudding user response:
By taking advantage of the fact that you are trying to sort the grouping keys, you can group by and sort at the same time by using a sorted map such as TreeMap
.
Specify the map that you want groupBy
to use by using groupByTo
.
val map = products.groupByTo(TreeMap()) { it.category }
As groupByTo
creates groups and puts the categories into the map, the keys will automatically be used to build a Red Black Tree (which is what a TreeMap
is under the hood). Traversing map.keys
will get you the keys in sorted order.