Replace each element in a list Here is how to transform a Zorglub (it is an API that I can not modify):

Zorglub transformedZorglub = zorglub.transform()


I am given a java.util.List&lt;Zorglub&gt; and I must transform them all, then afterwards I will perform more operations on the transformed Zorglubs. After transformation I never use the originals anymore. This question is only about the transformation part. I wrote this:

List&lt;Zorglub&gt; transformedZorglubs = new ArrayList&lt;Zorglub&gt;(zorglubs.size())
zorglubs.each {
    transformedZorglubs.add(
        it.transform()
    )
}
zorglubs = transformedZorglubs


Is there something smarter or more elegant to do?

In particular, something that would avoid creating a new list and using twice as much memory, while avoiding bugs that often arise when modifying a list while iterating over it?
To replace the elements in-place without building a new list,
you would need to reassign the elements at each index, that is,
essentially zorglubs[i] = zorglubs[i].transform() for each index i in the list.

A perhaps elegant way to do this is using the eachWithIndex function,
which gives you access to each element and its index:

zorglubs.eachWithIndex { it, index -&gt; zorglubs[index] = it.transform() }