I have a HashMap and I\'d like to iterate they key-value pairs in a different random order each time i get the iterator. Conceptually I\'d like to \"shuffle\" the map before
Actually you do not need to shuffle at all:
Just draw a random index in an array of keys and remove the key by overwritting with the last:
public class RandomMapIterator implements Iterator {
private final Map map;
private final K[] keys;
private int keysCount;
@SuppressWarnings("unchecked")
public RandomMapIterator(Map map) {
this.map = map;
this.keys = (K[]) map.keySet().toArray();
this.keysCount = keys.length;
}
@Override
public boolean hasNext() {
return keysCount!=0;
}
@Override
public V next() {
int index = nextIndex();
K key = keys[index];
keys[index] = keys[--keysCount];
return map.get(key);
}
protected int nextIndex() {
return (int)(Math.random() * keysCount);
}
@Override
public void remove() {
throw new UnsupportedOperationException();
}
}