热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

从Java中的Map中选择随机键和值集-SelectingrandomkeyandvaluesetsfromaMapinJava

IwanttogetrandomkeysandtheirrespectivevaluesfromaMap.Theideaisthatarandomgenerato

I want to get random keys and their respective values from a Map. The idea is that a random generator would pick a key and display that value. The tricky part is that both key and value will be strings, for example myMap.put("Geddy", "Lee").

我想从Map获取随机密钥及其各自的值。这个想法是随机生成器会选择一个键并显示该值。棘手的部分是键和值都是字符串,例如myMap.put(“Geddy”,“Lee”)。

8 个解决方案

#1


47  

HashMap x;

Random       random    = new Random();
List keys      = new ArrayList(x.keySet());
String       randomKey = keys.get( random.nextInt(keys.size()) );
String       value     = x.get(randomKey);

#2


4  

This question should be of help to you Is there a way to get the value of a HashMap randomly in Java? and this one also Picking a random element from a set because HashMap is backed by a HashSet. It would be either O(n) time and constant space or it would be O(n) extra space and constant time.

这个问题应该对你有所帮助有没有办法在Java中随机获取HashMap的值?这个也从一个集中挑选一个随机元素,因为HashMap由一个HashSet支持。它可以是O(n)时间和恒定空间,也可以是O(n)额外空间和恒定时间。

#3


3  

If you don't mind the wasted space, one approach would be to separately keep a List of all keys that are in the Map. For best performance, you'll want a List that has good random-access performance (like an ArrayList). Then, just get a random number between 0 (inclusive) and list.size() (exclusive), pull out the key at that index, and look that key up.

如果您不介意浪费的空间,一种方法是单独保留Map中所有键的List。为了获得最佳性能,您需要一个具有良好随机访问性能的List(如ArrayList)。然后,只需获得0(含)和list.size()(不包括)之间的随机数,拉出该索引处的键,然后查看该键。

Random rand = something
int randIndex = rand.nextInt(list.size());
K key = list.get(randIndex);
V value = map.get(key);

This approach also means that adding a key-value pair is a good deal cheaper than removing one. To add the key-value pair, you would test to see if the key is already in the map (if your values can be null, you'll have to separately call map.containsKey; if not, you can just add the key-value pair and see if the "old value" it returns is null). If the key is already in the map, the list is unchanged, but if not, you add the key to the list (an O(1) operation for most lists). Removing a key-value pair, though, involves an O(N) operation to remove the key from the list.

这种方法也意味着添加键值对比删除键值便宜。要添加键值对,您将测试键是否已经在地图中(如果您的值可以为null,则必须单独调用map.containsKey;如果不是,您只需添加键 - 值对并查看它返回的“旧值”是否为空)。如果密钥已经在映射中,则列表将保持不变,但如果不是,则将密钥添加到列表中(对于大多数列表,为O(1)操作)。但是,删除键值对涉及O(N)操作以从列表中删除键。

If space is a big concern, but performance is less so, you could also get an Iterator over the map's entry set (Map.entrySet()), and skip randIndex entries before returning the one you want. But that would be an O(N) operation, which kinda defeats the whole point of a map.

如果空间是一个很大的问题,但性能不那么重要,你也可以在地图的入口集(Map.entrySet())上获得一个迭代器,并在返回你想要的那个之前跳过randIndex条目。但这将是一个O(N)操作,它有点击败了地图的整个点。

Finally, you can just get the entry set's toArray() and randomly index into that. That's simpler, though less efficient.

最后,您可以获取条目集的toArray()并随机索引到该条目。这更简单,但效率更低。

#4


2  

if your keys are integer, or something comparable, you can use TreeMap to do that.

如果你的键是整数或类似的东西,你可以使用TreeMap来做到这一点。

TreeMap treeMap = new TreeMap<>();
int key = RandomUtils.ranInt(treeMap.lastKey());
int value = treeMap.ceilingKey(key);

#5


1  

I would copy the Map into an array and select the entry you want at random. This avoid the need to also lookup the value from the key.

我会将Map复制到一个数组中并随机选择你想要的条目。这样就无需从密钥中查找值。

Map x = new HashMap();
Map.Entry[] entries = x.entrySet().toArray(new Map.Entry[0]);
Random rand = new Random();

// call repeatedly
Map.Entry keyValue = entries[rand.nextInt(entries.length)];

If you want to avoid duplication, you can randomize the order of the entries

如果要避免重复,可以随机化条目的顺序

Map x = new HashMap();
List> entries = new ArrayList> (x.entrySet());
Collections.shuffle(entries);
for (Map.Entry entry : entries) {
    System.out.println(entry);
}

#6


1  

Use reservoir sampling to select a list of random keys, then insert them into a map (along with their corresponding values in the source map.)

使用油藏采样选择随机键列表,然后将它们插入地图(以及源地图中的相应值)。

This way you do not need to copy the whole keySet into an array, only the selected keys.

这样您就不需要将整个keySet复制到一个数组中,只需复制选定的键。

public static Map sampleFromMap(Map source, int n, Random rnd) {
    List chosenKeys = new ArrayList();
    int count = 0;
    for (K k: source.keySet()) {
        if (count++  result = new HashMap();
    for (K k: chosenKeys) {
        result.put(k, source.get(k));
    }
    return Collections.unmodifiableMap(result);
}

#7


0  

In some cases you might want to preserve an order you put the elements in the Set,
In such scenario you can use, This 

Set alldocsId = new HashSet<>();
            for (int i=0;i alldocIDlst = new ArrayList<>();
        Iterator it = alldocsId.iterator();
        while (it.hasNext())
        {
            alldocIDlst.add(Integer.valueOf(it.next().toString()));
        }

#8


-1  

Been a while since a played with java, but doesn't keySet() give you a list that you can select from using a numerical index? I think you could pick a random number and select that from the keySet of myMap, then select the corresponding value from myMap. Can't test this right now, but it seems to strike me as possible!

自从玩过java以来​​已经有一段时间了,但是keySet()没有给你一个可以使用数字索引选择的列表吗?我想你可以选择一个随机数并从myMap的keySet中选择,然后从myMap中选择相应的值。现在无法测试,但它似乎尽可能地打击我!


推荐阅读
  • vue使用
    关键词: ... [详细]
  • Iamtryingtomakeaclassthatwillreadatextfileofnamesintoanarray,thenreturnthatarra ... [详细]
  • IhaveconfiguredanactionforaremotenotificationwhenitarrivestomyiOsapp.Iwanttwodiff ... [详细]
  • ALTERTABLE通过更改、添加、除去列和约束,或者通过启用或禁用约束和触发器来更改表的定义。语法ALTERTABLEtable{[ALTERCOLUMNcolu ... [详细]
  • Java太阳系小游戏分析和源码详解
    本文介绍了一个基于Java的太阳系小游戏的分析和源码详解。通过对面向对象的知识的学习和实践,作者实现了太阳系各行星绕太阳转的效果。文章详细介绍了游戏的设计思路和源码结构,包括工具类、常量、图片加载、面板等。通过这个小游戏的制作,读者可以巩固和应用所学的知识,如类的继承、方法的重载与重写、多态和封装等。 ... [详细]
  • Spring特性实现接口多类的动态调用详解
    本文详细介绍了如何使用Spring特性实现接口多类的动态调用。通过对Spring IoC容器的基础类BeanFactory和ApplicationContext的介绍,以及getBeansOfType方法的应用,解决了在实际工作中遇到的接口及多个实现类的问题。同时,文章还提到了SPI使用的不便之处,并介绍了借助ApplicationContext实现需求的方法。阅读本文,你将了解到Spring特性的实现原理和实际应用方式。 ... [详细]
  • ZSI.generate.Wsdl2PythonError: unsupported local simpleType restriction ... [详细]
  • 自动轮播,反转播放的ViewPagerAdapter的使用方法和效果展示
    本文介绍了如何使用自动轮播、反转播放的ViewPagerAdapter,并展示了其效果。该ViewPagerAdapter支持无限循环、触摸暂停、切换缩放等功能。同时提供了使用GIF.gif的示例和github地址。通过LoopFragmentPagerAdapter类的getActualCount、getActualItem和getActualPagerTitle方法可以实现自定义的循环效果和标题展示。 ... [详细]
  • 前景:当UI一个查询条件为多项选择,或录入多个条件的时候,比如查询所有名称里面包含以下动态条件,需要模糊查询里面每一项时比如是这样一个数组条件:newstring[]{兴业银行, ... [详细]
  • Java学习笔记之面向对象编程(OOP)
    本文介绍了Java学习笔记中的面向对象编程(OOP)内容,包括OOP的三大特性(封装、继承、多态)和五大原则(单一职责原则、开放封闭原则、里式替换原则、依赖倒置原则)。通过学习OOP,可以提高代码复用性、拓展性和安全性。 ... [详细]
  • 本文介绍了iOS数据库Sqlite的SQL语句分类和常见约束关键字。SQL语句分为DDL、DML和DQL三种类型,其中DDL语句用于定义、删除和修改数据表,关键字包括create、drop和alter。常见约束关键字包括if not exists、if exists、primary key、autoincrement、not null和default。此外,还介绍了常见的数据库数据类型,包括integer、text和real。 ... [详细]
  • Oracle Database 10g许可授予信息及高级功能详解
    本文介绍了Oracle Database 10g许可授予信息及其中的高级功能,包括数据库优化数据包、SQL访问指导、SQL优化指导、SQL优化集和重组对象。同时提供了详细说明,指导用户在Oracle Database 10g中如何使用这些功能。 ... [详细]
  • 本文讨论了一个关于cuowu类的问题,作者在使用cuowu类时遇到了错误提示和使用AdjustmentListener的问题。文章提供了16个解决方案,并给出了两个可能导致错误的原因。 ... [详细]
  • http:my.oschina.netleejun2005blog136820刚看到群里又有同学在说HTTP协议下的Get请求参数长度是有大小限制的,最大不能超过XX ... [详细]
  • 本文介绍了UVALive6575题目Odd and Even Zeroes的解法,使用了数位dp和找规律的方法。阶乘的定义和性质被介绍,并给出了一些例子。其中,部分阶乘的尾零个数为奇数,部分为偶数。 ... [详细]
author-avatar
lantshirt
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有