java random values that not repeat

2019-08-07 09:29发布

问题:

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

    }

回答1:

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.



回答2:

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:

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.



回答4:

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