Get Random Element from Collection

Tags:



I have a Collection<Obj> how do I get a random Obj from it?

I’ve checked the docs and there doesn’t seem to be a way, since iterator is the only way to access the collection. Do I have to iterate over it to get a random object!?

Answer

The most efficient it to only iterate as far as you need.

public static <T> T random(Collection<T> coll) {
    int num = (int) (Math.random() * coll.size());
    for(T t: coll) if (--num < 0) return t;
    throw new AssertionError();
}


Source: stackoverflow