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

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

    How about wrapping HashMap in another implementation of Map? The other map maintains a List, and on put() it does:

    if (inner.put(key, value) == null) listOfKeys.add(key);
    

    (I assume that nulls for values aren't permitted, if they are use containsKey, but that's slower)

提交回复
热议问题