Getting all key-value pairs from a hashmap in a random order
Sandeep Chawla
Greenhorn
Joined: Nov 15, 2009
Posts: 2
posted
0
In my iterator i want
1) every key-value pair is retrieved only once.
2) all key-value pairs are retrieved in one iteration of the hashmap
3)every time i run my iterator i get a different sequence of key-value pairs
The easiest approach I can think of off the top of my head is:
- Keep all your keys in a separate List - use Collections.shuffle() to randomise the List - Iterate through the List and pull out the corresponding values from the Map
Matthew Brown wrote:The easiest approach I can think of off the top of my head is:
- Keep all your keys in a separate List - use Collections.shuffle() to randomise the List - Iterate through the List and pull out the corresponding values from the Map
Is that any good?
One does not need to keep a separate List. Each time just create an ArrayList constructed using the set of (key,value) pairs obtained from Map.entrySet() and then shuffle the ArrayList.
Retired horse trader.
Note: double-underline links may be advertisements automatically added by this site and are probably not endorsed by me.
James Sabre wrote:One does not need to keep a separate List. Each time just create an ArrayList constructed using the set of (key,value) pairs obtained from Map.entrySet() and then shuffle the ArrayList.
It depends on the map implementation. Maps are allowed to use Map.Entry as a view for the current entry while iterating. I quote from the Javadoc of Map.Entry:
These Map.Entry objects are valid only for the duration of the iteration; more formally, the behavior of a map entry is undefined if the backing map has been modified after the entry was returned by the iterator, except through the setValue operation on the map entry.