Groovy is extremely powerful managing collections. I have a list like this one:
def nameList = ["Jon", "Mike", "Alexia"]
What I am trying to do is iterating 10 times to get ten people with a random name from the first list.
10.times{
Person person = new Person(
name: nameList.get() //I WANT TO GET A RANDOM NAME FROM THE LIST
)
}
This is not working for two obvious reasons, I am not adding any index in my nameList.get and I am not creating 10 different Person objects.
Just use the Java method Collections.shuffle()
like
class Person {
def name
}
def nameList = ["Jon", "Mike", "Alexia"]
10.times {
Collections.shuffle nameList // or with Groovy 3: nameList.shuffle()
Person person = new Person(
name: nameList.first()
)
println person.name
}
or use a random index like
class Person {
def name
}
def nameList = ["Jon", "Mike", "Alexia"]
def nameListSize = nameList.size()
def r = new Random()
10.times {
Person person = new Person(
name: nameList.get(r.nextInt(nameListSize))
)
println person.name
}