What's the best way to get a random element from a Collection? I've heard iteration in the best, so I've done the following:
Collection<Integer> c = new HashSet<Integer>();
Random r = new Random();
for (int i = 0; i < 100000; i++){
c.add(r.nextInt());
}
Iterator<Integer> i = c.iterator();
int random = r.nextInt(c.size());
int num = 0;
int count = 1;
while(i.hasNext()){
num = i.next();
if (count == random){
break;
}
count++;
}
System.out.println(num);
It works fine, as far as I can tell and only takes a couple of milliseconds to complete. However, I've been told that the above is overcomplicating the problem. I know you can convert the collection to an array or in Java 8 you can use streams.