I\'m working with a large ArrayList
, and I would repeatedly need to select a random key from a random HashMap (and do some stuff with it).
Since Java 8, there is an O(log(N)) approach with O(log(N)) additional memory: create a Spliterator
via map.entrySet().spliterator()
, make log(map.size()) trySplit()
calls and choose either the first or the second half randomly. When there are say less than 10 elements left in a Spliterator
, dump them into a list and make a random pick.