java 你如何洗牌地图中的元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6017338/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 13:59:37  来源:igfitidea点击:

How do you shuffle elements in a Map

java

提问by Joe

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

你如何洗牌 Map 中的元素,我正在寻找类似于该Collections.shuffle方法的东西。

回答by Lukas Eder

A Mapis not really ordered like a List, which means you cannot access Mapitems by index. Hence shuffling doesn't make sense in general. But what you could do is this (I omitted generics for the example):

AMap并没有真正像 a 那样排序List,这意味着您不能Map按索引访问项目。因此,改组通常没有意义。但是你可以做的是这个(我在例子中省略了泛型):

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

回答by Enrico Giurin

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.

没有必要对 HashMap 的键进行混洗,因为 HashMap 不会在其键中保留任何顺序(既不是自然顺序也不是插入顺序)。如果我们谈论的是保持插入顺序的 LinkedHashMap,这个问题是有道理的。在这种情况下,您可以创建一个随机插入键的新 LinkedHashMap。

Then, assuming that map is your source map (LinkedHashMap), here the code to generate a new map(LinkedHashMap) , named shuffleMap, with the keys shuffled.

然后,假设该地图是您的源地图 (LinkedHashMap),这里的代码生成一个名为 shuffleMap 的新地图 (LinkedHashMap) ,其中键已混洗。

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