14

How do you shuffle elements in a Map, I am looking for something similar to the Collections.shuffle method.

Joe
  • 14,513
  • 28
  • 82
  • 144

2 Answers2

36

A Map is not really ordered like a List, which means you cannot access Map items by index. Hence shuffling doesn't make sense in general. But what you could do is this (I omitted generics for the example):

Map map = new HashMap();

// [...] fill the map

List keys = new ArrayList(map.keySet());
Collections.shuffle(keys);
for (Object o : keys) {
    // Access keys/values in a random order
    map.get(o);
}
Lukas Eder
  • 211,314
  • 129
  • 689
  • 1,509
7

There is no point to shuffle the keys of HashMap since HashMap doesn't preserve any order (neither natural nor insert) in its keys. Question makes sense if we're talking about LinkedHashMap, which maintains insertion order. In such a case you can create a new LinkedHashMap having the keys inserted randomly.

Then, assuming that map is your source map (LinkedHashMap), here the code to generate a new map(LinkedHashMap) , named shuffleMap, with the keys shuffled.

    List<Integer> list = new ArrayList<>(map.keySet());
    Collections.shuffle(list);

    Map<Integer, String> shuffleMap = new LinkedHashMap<>();
    list.forEach(k->shuffleMap.put(k, map.get(k)));
Enrico Giurin
  • 2,183
  • 32
  • 30
  • HashMap doesn't *guarantee* any order but in my experiments, I found out that order of retrieval was the same in many-many-many(in fact, always) executions. Is this weird?? – Bikash Gyawali May 08 '17 at 09:12
  • @bikashg Try this: Map map = new HashMap<>(); map.put(4, ""); map.put(3, ""); map.forEach((k,v)-> System.out.println(k)); The order of insertion is not guarantee. – Enrico Giurin Aug 11 '17 at 22:44
  • 1
    @bikashg The order may change if you add/remove an element. It is then preserved for subsequent iterations until you modify the map again (and the map needs to be re-hashed). – Genhis Dec 24 '18 at 09:07