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