I have two Lists and I want to get the List containing only the elements in the first list that are not in the second one. The problem is that I need to specify a custom equal
when subtracting. Let's suppose I want to use one of the fields in the entries of the lists. Let's say the id
.
I implemented it this way:
list1.filter { log -> list2.none { it.id == log.id } }
or
val projection = logEntries.map { it.id }
list1.filter { it.id !in projection }
Is there a better way to do it? Please take into account that I can't set a new equal
method for the class.
In kotlin, we can use the + and - operators to add or subtract multiple collections. The first operand is a collection and the second operand is a collection or an element.
The way you do it is ok, but when the lists become bigger you might want to do that:
You could make the process more efficient by turning your reference list (list2
) to a set first.
val referenceIds = list2.distinctBy { it.id }.toSet()
list1.filter { it.id !in referenceIds }
Background:
An ArrayList
which you are most likely using has a time complexity of O(n) when you check if an element is contained. So, if the list gets bigger, it will take longer.
A HashSet
on the other hand has a time complexity of O(1) when checking if an element is contained. So, if list2
becomes bigger it won't get slower.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With