Java - creating permutations from hashmap keys

2019-08-04 19:21发布

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?

4条回答
疯言疯语
2楼-- · 2019-08-04 19:57

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

查看更多
男人必须洒脱
3楼-- · 2019-08-04 20:02

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.

查看更多
等我变得足够好
4楼-- · 2019-08-04 20:04

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.

查看更多
淡お忘
5楼-- · 2019-08-04 20:12

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

查看更多
登录 后发表回答