Issue
We can filter all items in a list that are also contained in another list by
list.filter(otherList::contains)
However, I want to filter all items in a list that are NOT contained in the other list. How can I negate the above?
Ofc, I can pass a lambda, for example
list.filter { !otherList.contains(it) }
but I looking for a better Kotlin-way approach.
Solution
Use the filterNot
to filter out items that are not contained in another list. This returns a list of elements for which the predicate yields false
.
val filteredList = list.filterNot { otherList.contains(it) }
The operation has a time complexity of O(n*m), where n is the size of the original list and m is the size of the other list. If performance becomes an issue due to large lists, consider converting otherList to a HashSet, which would allow for constant-time lookups:
val setFromOtherList = otherList.toHashSet()
val filteredList = list.filterNot { setFromOtherList.contains(it) }
The above code will perform faster for large lists because checking membership in a HashSet
is generally much quicker than checking membership in a List
.
Answered By - Keyboard Corporation
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.