Skip to main content.
A metaClass example of getting a random arraylist element

Yeah, yeah, OK, I can't name blog post titles very creatively :)

This is simply a repost of a blog post I did a few months ago, but I'm not sure many people here have read my other more generalized blog, so I'll repost the Groovyish content here now and then.

Someone recently asked how to get a random element from an array. In PHP it’s pretty straightforward - array_rand($x) - but there’s not (AFAICT) a built-in way in Groovy to do this. So I wrote a little something which should hopefully demonstrate the power of the metaClass stuff to boot.

ArrayList.metaClass.getRand = { number -> if(number==0) { return delegate[new Random().nextInt(delegate.size)] } else { def tempList = [] def counter = 0 while(counter>number) { tempList.add(delegate[new Random().nextInt(delegate.size)]) counter } return tempList } } def names = ['mike','matt','mark','lesley','jean','ron','jeff','martine'] println names.getRand() println names.getRand(5)

The first call to getRand() on the names list will just return one name from the list. The second will return 5 random entries (and some could theoretically be repeated). I’ve added this getRand() method to the base ArrayList class at runtime, even though it’s likely declared ‘final’ in Java’s base libraries. This is one of the core powers of Groovy, and is pretty slick, imo.



Comments on "A metaClass example of getting a random arraylist element"

Matthew Taylor
Great minds think alike ;). Here is a class I use as a Category or Mixin for Groovy Lists:

class RandomListUtils {

static def r = new Random()

static def rand(List self) {
self[r.nextInt(self.size())]
}

static def rand(List self, count) {
def newList = self.collect { it }
def result = []
count.times {
def randItem = newList.rand()
result
 

 

Michael Kimsal
Note - this blog thing takes < div > tags and such - I do < div style='background-color:#ccc'> around code blocks.
 
Matthew Taylor
Yeah, my comment was actually cut off somewhere within the code. :(
 
Viagra Without Prescription
great information dude, definitely something that is really useful, now I can complete some projects, with this in my hands I have the chance to do something interesting.
 

 

Add a comment

Your Name:
Your Homepage:
Comment:


Allowable HTML: <br> <i> <p> <b>