Top community members
All Wiki Articles Create Wiki Article

Have you ever heard about encyclopedia for code?

What about: Wiki for Code project?

* because I've tried to share code and my solutions on different services and it was removed or I was unwelcomed
   - maybe it wasn't good place, but this one is.

if you think you have solution that can help someone, you are welcome to share this solution - Click here

Java - generate set with 10 random unique numbers

0 contributions
3 points

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

0 contributions

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more