Kotlin 1.5.42
I have the following data class and I need to filter out level 2 and level 3 values. Then I use a for..loop to loop through the level2 and check that the level3 has a parentId that matches the level2 value
Which is added to a list. When that level3 loop has finished I add to map with the key being the level2 object and the value being the list of level3.
i.e.
Map<TopsProductFilterItem, List<TopsProductFilterItem>>
I was looking for a better solution that is more concise using kotlin and looking if associateBy, or assoicateWith would help.
data class TopsProductFilterItem(
val value: String = "",
val catalogSearchCustomAttribute: CatalogSearchCustomAttribute = CatalogSearchCustomAttribute(),
)
And the following data class that has the levels
data class CatalogSearchCustomAttribute(
val level: Int = 0,
val parentId: Int = 0)
As there can be many levels assigned to his class I am only interested in level 2 and level 3. So I have filtered them out as below.
private fun createMapOfLevelCategories(listOfTopsProductFilterItem: List<TopsProductFilterItem>) {
val listOfLevel2 = listOfTopsProductFilterItem.filter { topsProductFilterItem ->
topsProductFilterItem.catalogSearchCustomAttribute.level == 2
}
val listOfLevel3 = listOfTopsProductFilterItem.filter { topsProductFilterItem ->
topsProductFilterItem.catalogSearchCustomAttribute.level == 3
}
val mapOfCategoryLevel2 = mutableMapOf<TopsProductFilterItem, List<TopsProductFilterItem>>()
listOfLevel2.forEach { categoryLevel2 ->
/* Find the parent id in the level 3 and from the level 2 value */
val listOfCategoryLevel3 = mutableListOf<TopsProductFilterItem>()
listOfLevel3.forEach { categoryLevel3 ->
if(categoryLevel2.value.toInt() == categoryLevel3.catalogSearchCustomAttribute.parentId) {
/* found a matching parent ID and value */
listOfCategoryLevel3.add(categoryLevel3)
}
}
mapOfCategoryLevel2.put(categoryLevel2, listOfCategoryLevel3)
}
}