从列表中获取随机元素的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.
- 如何使用groovy从名称列表中获取随机元素?
- 我可以使用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
}