Here is an alternative way which uses a set and fills it until it grows to the size required. It generates numbersToDraw distinct random numbers in range from min to max (inclusive). It also preserves the order in which numbers were drawn (that is what LinkedHashSet is for).
private static Set<Integer> drawNumbers(int min, int max, int numbersToDraw) {
if (max < min) {
throw new IllegalArgumentException("Minimum must be less than maximum.");
}
if (max < 0 || min < 0) {
throw new IllegalArgumentException("Both range numbers must be positive.");
}
final int countOfNumbers = max - min + 1;
if (countOfNumbers < numbersToDraw) {
throw new IllegalArgumentException("Range is not big enough.");
}
final Random randomizer = new SecureRandom();
final Set<Integer> numbersDrawn = new LinkedHashSet<>();
while (numbersDrawn.size() < numbersToDraw) {
final int randomNumber = min + randomizer.nextInt(countOfNumbers);
numbersDrawn.add(randomNumber);
}
return numbersDrawn;
}
If you do not require numbers to be unique, you can use this in Java 8:
final Random randomizer = new SecureRandom();
final List<Integer> numbersDrawn = IntStream
.range(0, numbersToDraw)
.mapToObj(i -> min + randomizer.nextInt(max - min + 1))
.collect(Collectors.toList());
If you do not require numbers to be unique, BUT you want to print their distinct values (is that your original question?):
final Random randomizer = new SecureRandom();
final Set<Integer> numbersDrawn = IntStream
.range(0, numbersToDraw)
.mapToObj(i -> min + randomizer.nextInt(max - min + 1))
.collect(Collectors.toSet());
And one more alternative for your concrete case:
final Set<Integer> distinctNumbers = Arrays
.stream(lotteryNumbers)
.distinct() // you can leave this as the set is distinct automatically
.boxed()
.collect(Collectors.toSet());