Generating Unique Random Numbers in Java

后端 未结 21 2544
不思量自难忘°
不思量自难忘° 2020-11-21 07:45

I\'m trying to get random numbers between 0 and 100. But I want them to be unique, not repeated in a sequence. For example if I got 5 numbers, they should be 82,12,53,64,32

21条回答
  •  走了就别回头了
    2020-11-21 08:15

    Though it's an old thread, but adding another option might not harm. (JDK 1.8 lambda functions seem to make it easy);

    The problem could be broken down into the following steps;

    • Get a minimum value for the provided list of integers (for which to generate unique random numbers)
    • Get a maximum value for the provided list of integers
    • Use ThreadLocalRandom class (from JDK 1.8) to generate random integer values against the previously found min and max integer values and then filter to ensure that the values are indeed contained by the originally provided list. Finally apply distinct to the intstream to ensure that generated numbers are unique.

    Here is the function with some description:

    /**
     * Provided an unsequenced / sequenced list of integers, the function returns unique random IDs as defined by the parameter
     * @param numberToGenerate
     * @param idList
     * @return List of unique random integer values from the provided list
     */
    private List getUniqueRandomInts(List idList, Integer numberToGenerate) {
    
        List generatedUniqueIds = new ArrayList<>();
    
        Integer minId = idList.stream().mapToInt (v->v).min().orElseThrow(NoSuchElementException::new);
        Integer maxId = idList.stream().mapToInt (v->v).max().orElseThrow(NoSuchElementException::new);
    
                ThreadLocalRandom.current().ints(minId,maxId)
                .filter(e->idList.contains(e))
                .distinct()
                .limit(numberToGenerate)
                .forEach(generatedUniqueIds:: add);
    
        return generatedUniqueIds;
    
    }
    

    So that, to get 11 unique random numbers for 'allIntegers' list object, we'll call the function like;

        List ids = getUniqueRandomInts(allIntegers,11);
    

    The function declares new arrayList 'generatedUniqueIds' and populates with each unique random integer up to the required number before returning.

    P.S. ThreadLocalRandom class avoids common seed value in case of concurrent threads.

提交回复
热议问题