java随机值不重复 [英] java random values that not repeat

查看:70
本文介绍了java随机值不重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从 ArrayList 中选择几个随机值,但值不能重复。使用下面的代码,我只是选择随机值,但是可以重复。

I need to pick few random values from ArrayList, but values cannot duplicate. With code below i simply pick random values but they can duplicate.

    for (int i = 0; i < 5; i++) {

        index = random.nextInt(menuItems.size());
        HashMap<String, String> urls = new HashMap<String, String>();

        urls.put("Value", menuItems.get(index).get(KEY_URL));

        randomitems.add(urls);

    }


推荐答案

不需要按照特定的顺序保持 menutItems ,你可以简单地洗牌并取得前5个项目:

If you don't need to keep menutItems in a specific order, you can simply shuffle it and take the first 5 items:

Collections.shuffle(menuItems);
for (int i = 0; i < 5; i++) {
    HashMap<String, String> urls = new HashMap<String, String>();
    urls.put("Value", menuItems.get(i).get(KEY_URL));
    randomitems.add(urls);
}

如果您确实需要保留 menuItems 就是这样,你可以先复制一个副本。

If you do need to keep menuItems as it is, you can make a copy first.

这篇关于java随机值不重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆