Here is an alternative method that uses a set and fills it until it reaches the required size. It generates numbersToDraw various random numbers ranging from min to max (inclusive). It also preserves the order in which the numbers were drawn (this uses the LinkedHashSet).
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 want the 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 want the numbers to be unique, BUT you want to print your individual values ββ(is this 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 option for your specific case:
final Set<Integer> distinctNumbers = Arrays .stream(lotteryNumbers) .distinct() // you can leave this as the set is distinct automatically .boxed() .collect(Collectors.toSet());
voho source share