Joe
Joe

Reputation: 15331

How do you shuffle elements in a Map

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

Upvotes: 14

Views: 25124

Answers (2)

Enrico Giurin
Enrico Giurin

Reputation: 2273

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)));

Upvotes: 7

Lukas Eder
Lukas Eder

Reputation: 220842

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);
}

Upvotes: 36

Related Questions