Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you shuffle elements in a Map

Tags:

java

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

like image 915
Joe Avatar asked May 16 '11 12:05

Joe


People also ask

Can you shuffle a HashMap?

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.

How to shuffle array?

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.

How do you fetch all values on a map?

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.


2 Answers

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);
}
like image 67
Lukas Eder Avatar answered Sep 28 '22 18:09

Lukas Eder


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)));
like image 41
Enrico Giurin Avatar answered Sep 28 '22 18:09

Enrico Giurin