Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Groovy method to get a random element from a list

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.

  1. How can I get a random element from my name list using groovy?
  2. Can I create a list with 10 people with random names (in a simple way), using groovy's collections properties?
like image 652
Blazerg Avatar asked Sep 04 '17 09:09

Blazerg


People also ask

How do you get a random value from a list in Groovy?

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.

How do you get random elements from a list?

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.

How do I randomly select an item from a list in Java?

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.

How do you get the index of an element in a list in Groovy?

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.


1 Answers

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
}
like image 123
Vampire Avatar answered Sep 21 '22 19:09

Vampire