How to get random unique integers in a range with Java

If you are able to use Java 8 or up you can make use of the various methods of Random that return an IntStream.

E.g. if you want to generate random distinct numbers from a range [0, 100) you can use:

1
2
3
4
5
OfInt iterator = ThreadLocalRandom.current().ints(0, 100).distinct().iterator();
 
for (int i = 0; i < 100; i++) {
  System.out.println("Next random number: " + iterator.next());
}

Since our range contains 100 Integers and .distinct() was used we can’t draw more than 100 numbers from the stream!

One thought on “How to get random unique integers in a range with Java

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.