aspose file tools*
The moose likes Java in General and the fly likes Getting all key-value pairs from a hashmap in a random order Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Getting all key-value pairs from a hashmap in a random order" Watch "Getting all key-value pairs from a hashmap in a random order" New topic
Author

Getting all key-value pairs from a hashmap in a random order

Sandeep Chawla
Greenhorn

Joined: Nov 15, 2009
Posts: 2
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

can anybody suggest how to go for it?
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4363
    
    8

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?
James Sabre
Ranch Hand

Joined: Sep 07, 2004
Posts: 781

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.
Matthew Brown
Bartender

Joined: Apr 06, 2010
Posts: 4363
    
    8

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.

Yes, I agree, that sounds better.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19670
    
  18

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.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Sandeep Chawla
Greenhorn

Joined: Nov 15, 2009
Posts: 2
Thanks everyone!

Matthews approach worked pretty well!! James' and Rob's solution proved quite useful too
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Getting all key-value pairs from a hashmap in a random order