I have a list:
val someList = listOf(1, 20, 10, 55, 30, 22, 11, 0, 99)
And I want to iterate it while modifying some of the values. I know I can do it with map
but that makes a copy of the list.
val copyOfList = someList.map { if (it <= 20) it + 20 else it }
How do I do this without a copy?
Note: this question is intentionally written and answered by the author (Self-Answered Questions), so that the idiomatic answers to commonly asked Kotlin topics are present in SO. Also to clarify some really old answers written for alphas of Kotlin that are not accurate for current-day Kotlin.
Here's what I came up with, which is a similar approach to Jayson:
First, not all copying of a list is bad. Sometimes a copy can take advantage of CPU cache and be extremely fast, it depends on the list, size, and other factors.
Second, for modifying a list "in-place" you need to use a type of list that is mutable. In your sample you use
listOf
which returns theList<T>
interface, and that is read-only. You need to directly reference the class of a mutable list (i.e.ArrayList
), or it is idiomatic Kotlin to use the helper functionsarrayListOf
orlinkedListOf
to create aMutableList<T>
reference. Once you have that, you can iterate the list using thelistIterator()
which has a mutation methodset()
.This will change the values in the list as iteration occurs and is efficient for all list types. To make this easier, create helpful extension functions that you can re-use (see below).
Mutating using a simple extension function:
You can write extension functions for Kotlin that do an in place mutable iteration for any
MutableList
implementation. These inline functions will perform as fast as any custom use of the iterator and is inlined for performance. Perfect for Android or anywhere.Here is a
mapInPlace
extension function (which keeps the naming typical for these type of functions such asmap
andmapTo
):Example calling any variation of this extension function:
This is not generalized for all
Collection<T>
, because most iterators only have aremove()
method, notset()
.Extension functions for Arrays
You can handle generic arrays with a similar method:
And for each of the primitive arrays, use a variation of:
About the Optimization using only Reference Equality
The extension functions above optimize a little by not setting the value if it has not changed to a different instance, checking that using
===
or!==
is Referential Equality. It isn't worth checkingequals()
orhashCode()
because calling those has an unknown cost, and really the referential equality catches any intent to change the value.Unit Tests for Extension Functions
Here are unit test cases showing the functions working, and also a small comparison to the stdlib function
map()
that makes a copy: