Groovy method to get a random element from a list
12,656
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
}
Author by
Blazerg
Updated on June 13, 2022Comments
-
Blazerg almost 2 years
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.
- How can I get a random element from my name list using groovy?
- Can I create a list with 10 people with random names (in a simple way), using groovy's collections properties?
-
Berg over 6 yearsIsn't the first suggestion a bit expensive?
-
Vampire over 6 yearsNot really. Just for you I made a quick measure. I commented out the
println
as it is the same in both and output usually is expensive and increased the10
to100_000_000
, usingSystem.currentTimeMillis()
for measuring the time both variants need. The first one needed 32 seconds, the second one 30 seconds, so not too much of a difference for the iterations imho. Besides that if you need performance, don't use Groovy, but Assembler. ;-) Basically it is is 1. version more object oriented vs 2. version slightly more performant like often. There may even faster ones, but that wasn't asked. -
Berg over 6 yearsNah, this first is much slower, regardless of programming language used: If you take a list of 1000 names and run it 100,000 times the first approach takes 3.6 s and the second 0.8. Not a surprise because the first loop has to randomise all elements of the list while the second only one element.
-
Vampire over 6 yearsWell, as I seid, like often it is more object oriented code vs. more performance. And OP did not say how important performance is, so I provided both alternatives. Besides that, you can also shuffle once and then take one after the other until the collection is exhausted and the shuffle again. But that is slightly different semantic then, as the names will not repeat before the collection is exhausted.
-
Janesh Kodikara almost 3 years
Collections.shuffle nameList
can be replaced withnameList.shuffle()
-
zett42 over 2 yearsGroovy 3.0 adds methods
shuffle()
(mutating) andshuffled()
(non-mutating) to arrays and lists. blog.mrhaki.com/2020/02/…