Is there a way to get the value of a HashMap randomly in Java?

前端 未结 13 2160
心在旅途
心在旅途 2020-11-30 03:45

Is there a way to get the value of a HashMap randomly in Java?

13条回答
  •  没有蜡笔的小新
    2020-11-30 04:08

    It depends on what your key is - the nature of a hashmap doesn't allow for this to happen easily.

    The way I can think of off the top of my head is to select a random number between 1 and the size of the hashmap, and then start iterating over it, maintaining a count as you go - when count is equal to that random number you chose, that is your random element.

提交回复
热议问题