Need to make a particular filter on a list (Android Kotlin)

Viewed 34

I have 2 lists with 2 differents Object.

First list ==> data class ObjectA ( val id: String?, val label: String?, val dueDate: LocalDate? )

And Second list ==> data class ObjectB ( val id: String = "", val clientLabel: String = "", val productLabel: String = "", val amount: ColoredAmount )

And I need to filter the ObjectA list with the ID common values between ObjectB List and ObjectA.

I don't find the simple solution.

Thanks very much for your help.

Regards Bomatch

1 Answers

This is the simplest approach I could find. The lists are named listA and listB:

var filteredList = listA.filter { objectA -> listB.any{ objectB -> objectB.id == objectA.id} }

I'll try to decompose and explain it step by step:

  1. listA.filter { objectA -> ... }traverses objects in listA (renamed as objectA) and returns a new list containing only the objects that fulfill the condition on the right (...)
  2. istB.any{ objectB -> objectB.id == objectA.id}returns a boolean indicating if ANY of the objects in listB (renamed as objectB) fulfill the condition of "being equal to the id of objectA"

So overall, for each object on listA you traverse listB to check if it contains and item with the same ID.

Hope it helps. Filtering lists can be complex to understand at first, so if you have any question leave them in the comment and I'll try to help again.

Related