我正在嘗試將我的嵌套 for 循環轉換為asSequence
Kotlin。在這裡,我的目標是從另一個具有相同 key 的對像數組中獲取和更新我所有對像數組的值。
嵌套 for 循環:
val myFields = getMyFields()
val otherFields = getOtherFields()
for (myField in myFields) { // loop tru the my fields
for (otherField in otherFields) { // find the same fields
if (myField.key == otherField.key) { // if the same, update the value
val updatedMyField = myField.copy(value = otherValue.value)
myFields[myFields.indexOf(myField)] = updatedMyField // update my field value
break
}
}
}
我試過的:
val updatedMyFields = getMyFields().asSequence()
.map { myField ->
getOtherFields().asSequence()
.map { otherField ->
if (myField.key == otherField.key) {
return@map otherField.value
} else {
return@map ""
}
}
.filter { it?.isNotEmpty() == true }
.first()?.map { myField.copy(value = it.toString()) }
}
.toList()
但這不會編譯,因為它會返回List<List<MyField>>
。
我只是為此尋找更清潔的東西。
正如評論所暗示的那樣,使用Map
.
(更準確地說,地圖解決方案所花費的時間與列表長度的總和成正比,而嵌套的 for 循環所花費的時間與其乘積成正比——這會更快地變大。)
這是這樣做的一種方法:
val otherFields = getOtherFields().associate{ it.key to it.value }
val myFields = getMyFields().map {
val otherValue = otherFields[it.key]
if (otherValue != null) it.copy(value = otherValue) else it
}
第一行Map
從“其他字段”鍵到它們的值創建一個。其餘的然後使用它從“我的字段”創建一個新列表,替換存在的“其他字段”中的值。
我不得不對類型 &c 做出假設,因為問題中的代碼不完整,但這也應該這樣做。顯然,您可以通過修改it.copy()
.
根據周圍的代碼,可能有更簡單、更有效的方法。如果您將其擴展為一個最小的、完整的和可驗證的示例——特別是一個說明您已經如何使用 a 的示例Map
,根據您的評論——我們可能會提出更好的建議。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句