Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subtract two Lists in Kotlin using a custom equal function

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.

like image 884
1048576 Avatar asked Feb 04 '19 09:02

1048576


People also ask

How do you subtract on Kotlin?

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.


1 Answers

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.

like image 94
Willi Mentzel Avatar answered Oct 18 '22 18:10

Willi Mentzel