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.
Groovy - random() The method is used to generate a random number between 0.0 and 1.0. The range is: 0.0 =< Math. random < 1.0. Different ranges can be achieved by using arithmetic.
Using random. randrange() to select random value from a list. random. randrange() method is used to generate a random number in a given range, we can specify the range to be 0 to the length of the list, and get the index, and then the corresponding value.
In order to get a random item from a List instance, you need to generate a random index number and then fetch an item by this generated index number using List. get() method. The key point here is to remember that you mustn't use an index that exceeds your List's size.
Groovy - indexOf() Returns the index within this String of the first occurrence of the specified substring. This method has 4 different variants. public int indexOf(int ch) − Returns the index within this string of the first occurrence of the specified character or -1 if the character does not occur.
Just use the Java method Collections.shuffle()
like
class Person {
def name
}
def nameList = ["Jon", "Mike", "Alexia"]
10.times {
Collections.shuffle nameList
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With