How do you shuffle elements in a Map, I am looking for something similar to the Collections.shuffle
method.
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.
Shuffle Array using Random Class We can iterate through the array elements in a for loop. Then, we use the Random class to generate a random index number. Then swap the current index element with the randomly generated index element. At the end of the for loop, we will have a randomly shuffled array.
If you only want to retrieve values, you can use the Map. values() method. It returns a Collection view of just the values contained in the map.
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);
}
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)));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With