Pemba Tamang
Pemba Tamang

Reputation: 1052

How to filter and sort a List using another List in kotlin

My code

val list1 = getAllCheckingPoints() 
val list2 = getselectedCheckingPoints()

say list1 is of Type1 and list2 is of Type2

Type1 is a data class that contains id,name,type,duration

Type2 is a data class that contains only id and position

both contain ids that match but only list 2 contains the positions

so I create an empty list

var filteredList: List<Type1> = emptyList()


 filteredList = list2.flatMap { list2Item->
                list1.filter { list1Item ->
                    list1Item.id == list2Item.id
                }
            }

Here I am trying is to make the filteredList a list of Type1 that has only the items from list1 that are present in list2 with matching the ids. I am stuck after this step.

how do I sort the filteredList with the position values present in list2 ?

Upvotes: 0

Views: 1679

Answers (1)

As far as I understood, you need filter out all items of list1 with ids absent in list2 and sort them based on some property of list2 object.

  1. Convert second list into map with key=id, value=position:
val map = list2.associate { it.id to it.position }
  1. Use this map for filtering and sorting:
val result = list1.filter { it.id in map }.sortedBy { map[it.id] }

Upvotes: 2

Related Questions