Languages
[Edit]
EN

Java - generate set with 10 random unique numbers

3 points
Created by:
halfera
411

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

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Java - random numbers

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join