# Replace each element in a list [closed]

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<Zorglub> 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<Zorglub> transformedZorglubs = new ArrayList<Zorglub>(zorglubs.size())
zorglubs.each {
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 -> zorglubs[index] = it.transform() }

zorglubs = zorglubs.collect{it.transform()} will a bit more elegantly but actually collect returns new array.