Lets say that i have a list of AccountDto (getContats() -> List)that each has a column accountId
List<Int> list = accountsDao.getContactIds()
and i have a list of MessageDto, where messageDto has a field 'fromAccountId'. I want to loop through the messageList and find what new fromAccountId i have that dont exist in my DB.
getAccounts().value?.let {
for ((every accountId from it.accountDto) in --(every fromAccountId in newMessages.list)--) {
if (it.contains(newFromAccountId))
println("fount $newFromAccountId")
}
}
Is there an elegant way to do that in Kotlin...?
You are using nested loops
which is not a very good idea, since time complexity of this operation is O(n^2)
, performace will degrade very fast as the size of your lists
increase.
Better approach on the expense of some extra memory would be to first create a set
of all the accountId's from your Database
, and then iterate
over the messageList
and for every accoutId
check if the set
contains this accountId
.
// Store all the accountId's in a Set so that lookup is fast
var accountIds = getAccounts().map{it.accountId}.toSet()
// Iterate over the messageList and find the Id's that are not in Set
messageList.asSequence()
.filter { !accountIds.contains(it.fromAccountId) }
.forEach { println("fount $it") }