How to select a random key from a HashMap in Java?

前端 未结 9 1119
小鲜肉
小鲜肉 2021-02-05 05:03

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).

9条回答
  •  感情败类
    2021-02-05 06:06

    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.

提交回复
热议问题