Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How can I convert my Set to an array efficiently?

So I am trying to generate an array that is filled with unique randomized integers and I found out that doing this with an arraylist would be the most efficient way to do so.

public static int [] randArr(int n, int max){
       randArr = new int[n];
       Random rn = new Random();
       Set<Integer> test = new HashSet<Integer>();
       
      while(test.size() < n){
      test.add(rn.nextInt(0, max));
 
        }
}

Now I tried working with randArr = test.toArray() but I am not quite sure, what to put in the parentheses nor if this really can work. Is there any other method for converting, since I cannot simply assign randArr with the integers of test through test.get(i) with a for-loop either.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Don’t use a set. Stream the random numbers, remove dups using distinct, and limit using limit

public static int [] randArr(int n, int max){
    Random rn = new Random();
    return rn.ints(0,max).distinct().limit(n).toArray(); 
}

Notes:

  • Make certain that n is <= max, otherwise you could be waiting a while.
  • max must be >= 1 (required by Random.ints method)

You may want to put in some code to enforce those invariants and throw an appropriate exception if not in compliance. Something like the following (or whatever makes sense to you).

if (n > max || max <= 0) {
   throw new IllegalArgumentException(
                "n(%d) <= max(%d) or max > 0 not in compliance"
                .formatted(n,max));
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading