Hi all. What will be the kotlin collection functi...
# android
a
Hi all. What will be the kotlin collection function to convert nested list into hashmap.
Copy code
data class Products(id){
	packList=ArrayList<Packs>
}

data class Pack(title: string, is_original: Boolean)

val list= productList.map { it.id  to  it.packlist.map{ if (it.is_original==true} it.title}
Note: ArrayList<Products> But Products= Arraylist<Pack> i.e I want a hashmap just like this ["1" , "[item1, item2, item3, item4]" ]
d
Can you outline the output type you're expecting?
Map<String, String>
?
a
Map<String, List<String>>
d
I believe you're looking for
associate
.
Just change you outer
map
with
associate
.
a
Let me try
associate
Copy code
if (it.is_original==true) it.title
But this if check is still bypassing, I just want to return list of those pack which have flag
is_original= true
d
Use filter.
f
it's a gold rule: First filtering then mapping
a
How do I filter first, because nested list is only accessible from outerList index i.e Products List ?
z
You can use
mapNotNull
to do a filter + map at the same time:
Copy code
productList.associate { (id, packlist) ->
  id to packlist.mapNotNull { (title, isOriginal) ->
    title.takeIf { isOriginal }
  }
}
👍 3
a
Thanks @Zach Klippenstein (he/him) [MOD]