Skip to content

Get Random Element from Collection

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!?



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();
8 People found this is helpful