Java - creating permutations from hashmap keys

坚强是说给别人听的谎言 提交于 2019-12-11 09:38:18

问题


So I have a hashmap that has keys and objects. I was wondering if it was possible to create a number of permutations with the keys. So for example if i had:

1 - Object1 2 - Object2 3 - Object3 4 - Object4

To get a random order. So one outcome may be:

3 - Object3 1 - Object1 2 - Object2 4 - Object4

So far i have:

Map<Integer, GeoPoint> mapPoints = new HashMap<Integer, GeoPoint>();
Map<Integer, GeoPoint> mapPointsShuffle = new HashMap<Integer, GeoPoint>();

    for (int t =0; t < 50; t ++){

        Collections.shuffle((List<?>) mapPoints);

        mapPointsShuffle.putAll(mapPoints);
    }

So the idea is to give me 50 random permutations. But it comes back with :

09-26 11:15:27.813: E/AndroidRuntime(20434): java.lang.ClassCastException: java.util.HashMap cannot be cast to java.util.List

Any ideas?


回答1:


java.util.HashMap does not implement java.util.List




回答2:


You should make a list from hashmap keys first:

List<Integer> keys = new List<Integer>(mapPoints.keySet());

Then you can shuffle the key list using the method in the Collections the way your post shows.

The last call of your loop makes no sense, however:

mapPointsShuffle.putAll(mapPoints);

Even if you re-shuffle the keys fifty times, this would add the same map entries to another map fifty times over, resulting in the map with which you have started, because hash maps are unordered.




回答3:


This link guides you in how to generate a list from a hashmap, get this instead of trying to shuffle the hashmap!!




回答4:


How can you cast a map to list?

Collections.shuffle((List) mapPoints);

Are you trying to shuffle the keys? For HashMap you can't predict the order in which keys will be returned. So, you better get the keys in a list and then shuffle.



来源:https://stackoverflow.com/questions/12599676/java-creating-permutations-from-hashmap-keys

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!