Groovy method to get a random element from a list

拜拜、爱过 提交于 2020-01-03 08:53:24

问题


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?

回答1:


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
}


来源:https://stackoverflow.com/questions/46033940/groovy-method-to-get-a-random-element-from-a-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!