Kotlin noob here, I'm trying to update the element in listFirst
by comparing some attribute (say, topicId
) of the elements from the listSecond
, both list contains the same type of element. I had the following code but it looks ugly to me. Is there anyway to make it look better or more efficient in Kotlin? Thank you! (The compiler version: java 8)
...
outputList = mutableListOf<MyObject>()
listFirst.forEach {
element1 ->
run {
val t = listSecond.firstOrNull { element1.topicId == it.topicId }
if (t != null) {
outputList.add(t)
} else {
outputList.add(element1)
}
}
}
return outputList
CodePudding user response:
The run
enclosure in your code is not being used for anything so you might as well remove it. Anyway, you can use map
and an elvis operator to reduce your code quite a bit:
return listFirst.map { element1 ->
listSecond.firstOrNull { element1.topicId == it.topicId } ?: element1
}
If these are long lists, it would be more efficient to create a Map out of the second list so you aren't having to iterate it repeatedly with firstOrNull
. This would change it from O(n^2) to O(n).
val mapSecond = listSecond.associateBy { it.topicId }
return listFirst.map { element1 ->
mapSecond[element1.topicId] ?: element1
}