• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

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

 
Sandeep Chawla
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 781
Java Netbeans IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Matthew Brown
Bartender
Posts: 4568
9
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 20661
65
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Sandeep Chawla
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks everyone!

Matthews approach worked pretty well!! James' and Rob's solution proved quite useful too
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic