Languages
[Edit]
EN

Java - generate set with 10 random unique numbers

3 points
Created by:
JustMike
3491

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

Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.