Is there a way to get the value of a HashMap randomly in Java?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
Usually you do not really want a random value but rather just any value, and then it's nice doing this:
Converting it to an array and then getting the value is too slow when its in the hot path.
so get the set (either the key or keyvalue set) and do something like:
Generate a random number between 0 and the number of keys in your
HashMap
. Get the key at the random number. Get the value from that key.Pseudocode:
If it's hard to implement this in Java, then you could create and array from this code using the
toArray()
function inSet
.I'm not really sure how to do the random number.
A good answer depends slightly on the circumstances, in particular how often you need to get a random key for a given map (N.B. the technique is essentially the same whether you take key or value).
i really don't know why you want to do this... but if it helps, i've created a RandomMap that automatically randomizes the values when you call values(), then the following runnable demo application might do the job...