Reputation: 137
I have a list of ids say of size 10 and I have another list of items I want an efficient way to remove items that match any of those 10 ids
val list=items.filter { id== 1||id==3... and so on but in a more efficient way }
thanks in advance
Upvotes: 0
Views: 221
Reputation: 137
You can use predicate and filterTo method
//list of things you don't want in your filtered list
val listOfIds= listOf(312,264,309,297,233,262,149,156,214,350,316,315)
//a predicate used in filterTo function
private val someFilteringCondition = { num: Int ->listOfIds.contains(num) }
//list that we will filter into (it will contains filtered list
private val filteredPublishers = mutableListOf<SegmentModel>()
items.filterNotTo(filteredPublishers,someFilteringCondition )
adpater?.publishersChanged(it)
now filteredPublishers list constains items that doesn't have mentioned ids
Upvotes: 0
Reputation: 18568
In case you are dealing with a MutableList
, you could modify it (or a copy of it) by using the methods removeAll
or retainAll
:
Keep all items in ids
that are not present in removeIds
:
fun main() {
val ids = mutableListOf(20, 30, 40, 42, 50, 60)
val removeIds = listOf(20, 30, 40, 50, 60)
ids.retainAll { it !in removeIds }
println(ids)
}
or remove all items from ids
that are present in removeIds
:
fun main() {
val ids = mutableListOf(20, 30, 40, 42, 50, 60)
val removeIds = listOf(20, 30, 40, 50, 60)
ids.removeAll { it in removeIds }
println(ids)
}
Both main
s reduce ids
to just [42]
in these examples and output exactly that.
Unfortunately, this will not work on immutable List
s, you would have to make it a MutableList
first, preferably by using toMutableList()
or anything similar.
Upvotes: 1
Reputation: 2935
Returns a list containing all elements of the original collection except the elements contained in the given elements collection:
fun main() {
val ids = listOf(20, 30, 40, 50, 60)
val removeIds = listOf(30, 60)
val result = ids - removeIds
println(result) // [20, 40, 50]
}
Or with substract:
val result = ids subtract removeIds
Upvotes: 4