Home > Enterprise >  Creation of sublist using filter is not working
Creation of sublist using filter is not working

Time:04-01

I am trying to extract from a list all element which are not in the sublist already created. I cannot make it work using .filterNot because it filtering on the overall data class store in the list.

var subList2 = allList.filterNot { subList1.contains(it) }.toMutableList()

but allList and subList are a list of data class defined as :

data class Food(
    var name: Name,
    var state: State
)

As of now, using this code, the sublist2 can contain food that are in sublist1 because state is different.

I want the filter to be done only on name so the sublist2 only contain food which is not in the sublist1 whatever the state is.

Any idea ?

CodePudding user response:

Try to map the subList1 names:

val subList1Names = subList1.map { it.name }
var subList2 = allList.filterNot { it.name in subList1Names }.toMutableList()
  • Related