从列表中获取随机元素的Groovy方法 [英] Groovy method to get a random element from a list

查看:572
本文介绍了从列表中获取随机元素的Groovy方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Groovy是管理集合的强大工具.我有一个像这样的清单:

Groovy is extremely powerful managing collections. I have a list like this one:

def nameList = ["Jon", "Mike", "Alexia"]

我想做的是迭代10次,从第一个列表中获得10个名字随机的人.

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

由于两个明显的原因,此方法不起作用,我没有在nameList.get中添加任何索引,也没有创建10个不同的Person对象.

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. 如何使用groovy从名称列表中获取随机元素?
  2. 我可以使用groovy的collections属性以简单的方式创建一个包含10个人的随机名称列表吗?

推荐答案

只需使用Java方法Collections.shuffle()之类的

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
}

或使用类似的随机索引

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
}

这篇关于从列表中获取随机元素的Groovy方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆