你如何在地图中改变元素 [英] How do you shuffle elements in a Map
本文介绍了你如何在地图中改变元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何在地图中随机播放元素,我正在寻找类似于 Collections.shuffle
方法的内容。
How do you shuffle elements in a Map, I am looking for something similar to the Collections.shuffle
method.
推荐答案
一个地图
实际上并没有像 List
那样订购,表示您无法按索引访问 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);
}
这篇关于你如何在地图中改变元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文