Usually I use the Deque for it's intended purpose but infrequently I need to choose a random element from it. I use the below code to do so, but it requires iterating through the Deque. Is there a more efficient way to do it?
Iterator<T> iterator = mDeque.iterator();
int target = mRand.nextInt(mDeque.size());
while (iterator.hasNext()) {
if (target == 0) {
chosenElement = iterator.next();
break;
} else {
iterator.next();
target--;
}
}
You could use an ArrayDeque, use toArray
and then use the index directly ([target]
for your example)