'How to skip an item in nested map based on When()
I want iterate over items
's data
and create a a new list of SomeData based on item.type
however when type is UNKNOWN
I need skip that element and not add to list. How can I achieve it? continue@map
is not working for collection
fun getListOfMyItems(
items: List<SomeData>,
): List<MyItem> {
return items.groupBy {
Instant.ofEpochMilli(it.timestamp)
.toYear()
}.map { element ->
val myItemsList = element.data.map{ item ->
val itemsList: SomeData = when (item.type) {
Type.FIRST -> doChangesOnDataForFIRSTandReturn(item)
Type.SECOND -> doChangesOnDataForSECONDandReturn(item)
Type.UNKNOWN -> //how skip item here and not add to itemsList?
}
myItemsList
}
MyItem(
items = myItemsList
)
}
}
Solution 1:[1]
I have given the solution as shown below here
fun getListOfMyItems(
items: List<SomeData>,
): List<MyItem> {
return items.groupBy {
Instant.ofEpochMilli(it.timestamp)
.toYear()
}.map { element ->
val myItemsList = element.data.mapNotNull foo@{ item ->
val itemsList: SomeData = when (item.type) {
Type.FIRST -> doChangesOnDataForFIRSTandReturn(item)
Type.SECOND -> doChangesOnDataForSECONDandReturn(item)
Type.UNKNOWN -> return@foo null
}
myItemsList
}
MyItem(
items = myItemsList
)
}
}
Solution 2:[2]
You could always filter out those values before you start iterating over the list.
items.filter { it.type == Type.UNKNOWN }
.groupBy{ ... }
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | stanley mbote |
Solution 2 | gRaduateToaster |