Use of find in foreach in kotlin
Solution 1:
No, this code is not optimal for the performence. But the fix is actually very easy - just change the type of the data structure you use.
The problem is that lists are not optimized for searching. For each item from listOne
we have to iterate over elements in listTwo
. As a result, the time complexity is O(N*M)
where N
and M
are sizes of listOne
and listTwo
accordingly. We can replace/convert listTwo
with a set. Sets are good for searching, they search in constant time, so the resulting time complexity is just O(N+M)
. M
for preparing a set and N
for iterating over listOne
and searching.
Additionally, your code can be greatly simplified by using mapIndexed()
and replacing find()
with simple in
:
val s = listTwo.toSet()
val secondList = listOne.mapIndexed { index, item ->
Second(index, item in s)
}
You can also create a set directly, using setOf()
instead of listOf()
.