Languages
[Edit]
EN

Java - generate set with 10 random unique numbers

3 points
Created by:
JustMike
26150

Generate set with 10 random unique numbers in Java.

int minVal = 50;
int maxVal = 100;
Set<Integer> unique = new HashSet<>();

while (unique.size() != 10) {
    int randInt = ThreadLocalRandom.current().nextInt(minVal, maxVal);
    unique.add(randInt);
}

// [64, 65, 82, 68, 70, 88, 89, 60, 78, 95]
System.out.println(unique.toString());

Code flow:

  1. Set random numbers minVal = 50 and maxVal = 100
  2. Until set size is not 10 add new random int - so we execute while logic until HashSet.size() != 10
  3. Generate random number between minVal = 50 and maxVal = 100
  4. HashSet will add new number only if it is new, if the number already exists in the HashSet then it will be ignored.
  5. Display results with sys out

To get the code for random min max long, float, double check post:
https://dirask.com/q/zjM2x1

There are other ways to generate random integer in range min-max, look at this post:
https://dirask.com/q/VjoP81

References

ThreadLocalRandom - Java docs
Random - Java docs

Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join