Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Negation of function reference in Kotlin

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading