How to copy a list in Groovy

groovy

Solution

You are using the spread operator (`*`), which is making a list out of each element. Remove that:

list1 = [1, 2, 3]
println list1

list2 = list1.collect()
assert list2 == [1, 2, 3]

Check out the doc for more info on that method.

Problem

I have the following Groovy list: ``` l = [1, 2, 3] println(l) ``` Which gives me: ``` [1, 2, 3] ``` Now I want to create a copy of this list: ``` println(l*.collect()) ``` But this gives me the following: ``` [[1], [2], [3]] ``` Apparently I got a list of lists. How can I create a list of the same objects as in the original list?

Original source