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

前端 未结 9 1231
小鲜肉
小鲜肉 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:45

    I'm assuming you are using HashMap as you need to look something up at a later date?

    If not the case, then just change your HashMap to an Array/ArrayList.

    If this is the case, why not store your objects in a Map AND an ArrayList so you can look up randomly or by key.

    Alternatively, could you use a TreeMap instead of HashMap? I don't know what type your key is but you use TreeMap.floorKey() in conjunction with some key randomizer.

提交回复
热议问题