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
Should you need to draw futher values from the map without repeating any elements you can put the map into a List and then shuffle it.
Here is an example how to use the arrays approach described by Peter Stuifzand, also through the
values()
-method:I wrote a utility to retrieve a random entry, key, or value from a map, entry set, or iterator.
Since you cannot and should not be able to figure out the size of an iterator (Guava can do this) you will have to overload the
randEntry()
method to accept a size which should be the length of the entries.This works:
If you want the random value to be a type other than an
Object
simply add a cast to the last line. So ifmyHashMap
was declared as:The last line can be:
The below doesn't work,
Set.toArray()
always returns an array ofObject
s, which can't be coerced into an array ofMap.Entry
.Since the requirements only asks for a random value from the
HashMap
, here's the approach:HashMap
has avalues
method which returns aCollection
of the values in the map.Collection
is used to create aList
.size
method is used to find the size of theList
, which is used by theRandom.nextInt
method to get a random index of theList
.List
get
method with the random index.Implementation:
The nice part about this approach is that all the methods are generic -- there is no need for typecasting.
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.