java random values that not repeat

2019-08-07 08:58发布

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

    }

4条回答
Lonely孤独者°
2楼-- · 2019-08-07 09:35

Yes, it is in the nature of randomness that the same number may be given again.

To get rid of that you have to manually check the new random number against previously recieved ones and throw all that you do not want.

查看更多
啃猪蹄的小仙女
3楼-- · 2019-08-07 09:36

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

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

查看更多
够拽才男人
4楼-- · 2019-08-07 09:36

I'm answering the title of your question here. I use a Set to make sure every number is unique and I don't stop adding numbers until it equals the size I want. Then I convert it to a List:

package com.sandbox;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Random;
import java.util.Set;

public class Sandbox {

    private static final int TOTAL_NUMBERS_I_WANT = 5;

    public static void main(String[] args) {
        Random random = new Random();
        Set<Integer> nonRepeatingRandomNumbers = new HashSet<Integer>();
        while (nonRepeatingRandomNumbers.size() < TOTAL_NUMBERS_I_WANT) {
            nonRepeatingRandomNumbers.add(random.nextInt());
        }
        List<Integer> result = new ArrayList<Integer>(nonRepeatingRandomNumbers);
        System.out.println(result);
    }
}
查看更多
放荡不羁爱自由
5楼-- · 2019-08-07 09:47

duplicate your list, so you dont mess up your old list

List<Object> randomList = new ArrayList<Object>(oldList);

pick one

int index = new Random().nextInt(randomList.size());
Object randomObj = randomList.get(index);
randomList.remove(index);

so every time you pick one, you cannot pick that one again.

查看更多
登录 后发表回答