1
\$\begingroup\$

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 {
    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?

\$\endgroup\$
2
\$\begingroup\$

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() }
\$\endgroup\$
0
\$\begingroup\$

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

\$\endgroup\$

Not the answer you're looking for? Browse other questions tagged or ask your own question.