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

前端 未结 9 1123
小鲜肉
小鲜肉 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 05:52

    If you absolutely need to access the Entry array in HashMap, you can use reflection. But then your program will be dependent on that concrete implementation of HashMap.

    As proposed, you can keep a separate list of keys for each map. You would not keep deep copies of the keys, so the actual memory denormalisation wouldn't be that big.

    Third approach is to implement your own Map implementation, the one that keeps keys in a list instead of a set.

提交回复
热议问题