Martin
Martin

Reputation: 2914

How to filter two lists in Kotlin?

I have two List<CustomObject> and I want to create filtered list which will contain only items from second list, which are not present in first list. Parameter for comparison is objectId which is unique String value.

Upvotes: 2

Views: 8379

Answers (2)

marstran
marstran

Reputation: 28066

First, get the IDs of the first list:

val firstListIds = firstList.map { it.objectId }. 

Then, filter the second list by checking if the ID is among the IDs of the first list:

val result = secondList.filter { it.objectId !in firstListIds }

Upvotes: 12

EpicPandaForce
EpicPandaForce

Reputation: 81588

I think the following might work well:

val firstListObjectIds = firstList.map { it.objectId }.toSet()
val filteredList = secondList.filter { !firstListObjectIds.contains(it.objectId) }

Upvotes: 3

Related Questions