java random values that not repeat

给你一囗甜甜゛ 提交于 2019-12-11 07:17:23

问题


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


来源:https://stackoverflow.com/questions/15258063/java-random-values-that-not-repeat

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!