user717043
user717043

Reputation: 129

Performant way to filter a list based on another one?

I need to filter the list of objects based on another. Let's say we have two classes

data class Entity(val id: Long, val name: String)
data class SecondEntity(val name, val status: String)

I am interested in the following situation to filter the list of entities based on the status of another

val entityList = ...
val secondEnitityList = ...

//This how I did it
entityList.filter { entity ->
     secondEntityList.any { sEntity
        sEntity.name == entity.name && sEntity.status == "SomeStatus"
 }
}

Is there a more performant way to do this?

Upvotes: 1

Views: 109

Answers (1)

Henry Twist
Henry Twist

Reputation: 5980

You could reduce this to O(n) with a HashSet, by first filtering (based on the status) secondListEntity into a set and then using that for name lookups. So something like this:

val names = HashSet<String>()
secondEntityList.forEach {

    if(it.status == "SomeStatus") names.add(it.name)
}

entityList.filter { names.contains(it.name) }

If you have multiple lists to filter based on the same secondEntityList then you can reuse this set. However it's worth taking into account that constructing the set incurs an extra O(n) space complexity.


If you had multiple fields to compare, this could be extended to include a data class to hold the fields and fill the set with those, instead of strings.

Upvotes: 2

Related Questions