Vivek Modi
06/03/2021, 5:54 PMdata class CategoryResponse(
val item: List<CategoryItem>
)
data class CategoryItem(
val id: Int,
val Category1: List<ItemOptions>? = null,
val Category2: List<ItemOptions>? = null,
val Category3: List<ItemOptions>? = null
)
data class ItemOptions(
val name: String? = null,
val url: String? = null
)
I have an enum class, which has 4 enum types
enum class CategoryType(val name :String){
ALL("ALL"),
Category1("Category1"),
Category2("Category2"),
Category3("Category3");
}
There is a category named ALL, so i need the list of all the data but I don't want any null values, and still want the data that other categories hold.
Example - the list consist of 5 elements
Desired output:
ALL : list-> [id : 1 , category1 : ”..”] , [id : 2 ,category2 : “..”] , [id : 3 ,category2 : ”..”] , [id : 4 ,category1 : “..”] , [id : 5 ,category3: “.."]
CATEGORY2: list -> [id : 2 , category2 : “..”] , [id : 3 , category2 : “..”]
(this list may or may not consist of more than 5 elements)
is there any way that this list won’t occupy a lot of memory, or duplicate the objects and could be more efficient.?Vivek Modi
06/03/2021, 5:54 PMJeff
06/03/2021, 10:51 PMval Category1: List<ItemOptions>? = null
fields to be a single field of
val category: Pair<CategoryType, List<ItemOptions>
or as separate fields
val category: CategoryType
val itemOptions: List<ItemOptions>
Since you have the constraint that only one category will be valid at a time you could flatten it like that.
Then the all / specific could simply be
categoryResponse.items
or
categoryResponse.items.filter{ it.category == CategoryType.Category1 }
Vivek Modi
06/04/2021, 8:13 AMval dataList = CategoryResponse( listOf( CategoryItem(1, listOf(ItemOptions("aa", "ww"), ItemOptions("aa22", "ww22")), null, null), CategoryItem(2, null, listOf(ItemOptions("bb", "qq")), null), CategoryItem(3, null, null, listOf(ItemOptions("cc", "ee"))), CategoryItem(4, null, null, listOf(ItemOptions("dd", "tt"), ItemOptions("dd22", "tt22"))) ) )
Vivek Modi
06/04/2021, 8:13 AMval categoriesList : List<CategoryItem> = dataList.item categoriesList.filter { list -> list.Category2 == CategoryType.Category2 }
Vivek Modi
06/04/2021, 8:13 AMComparison of incompatible enums 'List<ItemOptions>?' and 'CategoryType' is always unsuccessful
on list.Category2 == CategoryType.Category2
Jeff
06/04/2021, 3:46 PM.map{ it.Category2 }
if 2 is the one you filtered on.Vivek Modi
06/04/2021, 3:47 PMVivek Modi
06/04/2021, 3:48 PM