Return Set with random unique Integer numbers between min and max range I need set of random unique Integer numbers for my unit test. I implemented this method, however I'm not sure if this is best way to implement this.

private Set&lt;Integer&gt; getRandomUniqueNumberSet(Integer min, Integer max)
{
    Set&lt;Integer&gt; added = new LinkedHashSet&lt;Integer&gt;(); 
    for(int i = min; i &lt;= max; i++)
    {
        Integer index = ThreadLocalRandom.current().nextInt(min, max + 1);
        Boolean loop = false; 
        if(!added.add(index)) loop = true;
        while(loop)
        {
            index = ThreadLocalRandom.current().nextInt(min, max + 1);
            if(added.add(index)) loop = false;
        }
    }
    return added;
}


Example:

for(Integer index : getRandomUniqueNumberSet(2, 15))
{
    System.out.println("Index: " + index);
}


Results:

Index: 8
Index: 5
Index: 15
Index: 9
Index: 4
Index: 3
Index: 7
Index: 2
Index: 11
Index: 14
Index: 6
Index: 10
Index: 13
Index: 12
Generating unique random numbers within a range

A good way to generate unique random numbers within a range is to create a list with the desired unique numbers, and then shuffle it.

  private Set&lt;Integer&gt; getRandomUniqueNumberSet(int min, int max) {
    List&lt;Integer&gt; numbers = IntStream.rangeClosed(min, max).boxed().collect(Collectors.toList());
    Collections.shuffle(numbers);
    return new LinkedHashSet&lt;&gt;(numbers);
  }


Don't used boxed types when you don't need null values

This method takes Integer parameters, which may be null:


private Set&lt;Integer&gt; getRandomUniqueNumberSet(Integer min, Integer max)



But the implementation doesn't handle the case when these values are null.
And it doesn't make sense to support such ranges.
Change those types to primitive int.

The same goes for the local variables Integer index and Boolean loop.

Why ThreadLocalRandom?

As per the javadoc, "use of ThreadLocalRandom is particularly appropriate when multiple tasks use random numbers in parallel in thread pools". I doubt that's necessary in your use case, in which case I suggest to use an instance of Random instead.