Home > Mobile >  How to skip an item in nested map based on When()
How to skip an item in nested map based on When()

Time:05-14

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
            )
        }
}

CodePudding user response:

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
                )
            }
    }

CodePudding user response:

You could always filter out those values before you start iterating over the list.

items.filter { it.type == Type.UNKNOWN }
.groupBy{ ... }
  • Related