Search code examples
listgrailsrandomgroovy

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?

Solution

  • 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
    }