Here you can find the source of randomElement(Collection extends E> coll)
public static <E> E randomElement(Collection<? extends E> coll)
//package com.java2s; //License from project: Open Source License import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Random; public class Main { public static <E> E randomElement(Collection<? extends E> coll) { return randomElement(coll, new Random()); }//from www. ja v a2 s . com public static <E> E randomElement(Collection<? extends E> coll, Random rand) { if (coll.size() == 0) { return null; } int index = rand.nextInt(coll.size()); if (coll instanceof List) { return ((List<? extends E>) coll).get(index); } else { Iterator<? extends E> iter = coll.iterator(); for (int i = 0; i < index; i++) { iter.next(); } return iter.next(); } } }