如何迭代对象列表但在特定字段 Kotlin
How to iterate on a list of object but in specific field Kotlin
假设我有一个 AccountDto 列表(getContats() -> List),每个列表都有一个 accountId
List<Int> list = accountsDao.getContactIds()
我有一个 MessageDto 列表,其中 messageDto 有一个字段 'fromAccountId'。
我想遍历 messageList 并找到我的数据库中不存在的新 fromAccountId。
getAccounts().value?.let {
for ((every accountId from it.accountDto) in --(every fromAccountId in newMessages.list)--) {
if (it.contains(newFromAccountId))
println("fount $newFromAccountId")
}
}
在 Kotlin 中是否有一种优雅的方式来做到这一点...?
您正在使用嵌套 loops
,这不是一个好主意,因为此操作的时间复杂度为 O(n^2)
,性能会随着 lists
的大小而快速下降增加。
牺牲一些额外内存的更好方法是首先从您的 Database
创建所有 accountId 的 set
,然后 iterate
在 messageList
并且对于每个 accoutId
检查 set
是否包含此 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") }
假设我有一个 AccountDto 列表(getContats() -> List),每个列表都有一个 accountId
List<Int> list = accountsDao.getContactIds()
我有一个 MessageDto 列表,其中 messageDto 有一个字段 'fromAccountId'。 我想遍历 messageList 并找到我的数据库中不存在的新 fromAccountId。
getAccounts().value?.let {
for ((every accountId from it.accountDto) in --(every fromAccountId in newMessages.list)--) {
if (it.contains(newFromAccountId))
println("fount $newFromAccountId")
}
}
在 Kotlin 中是否有一种优雅的方式来做到这一点...?
您正在使用嵌套 loops
,这不是一个好主意,因为此操作的时间复杂度为 O(n^2)
,性能会随着 lists
的大小而快速下降增加。
牺牲一些额外内存的更好方法是首先从您的 Database
创建所有 accountId 的 set
,然后 iterate
在 messageList
并且对于每个 accoutId
检查 set
是否包含此 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") }