To generate a random unique number in Java, you typically use java.util.Random, ThreadLocalRandom, or SecureRandom for a single random value, and combine it with a Set or Collections.shuffle() when you need a sequence of non-repeating numbers. For example, ThreadLocalRandom.current().nextInt(1, 101) gives one random integer from 1 to 100, but uniqueness only matters when generating multiple numbers—so the real answer depends on whether you need one number or a series.
Why “Unique” Changes the Approach
A single random number is always unique by definition—there’s nothing to compare it against. The challenge appears when you need several random numbers without repeats, like lottery picks, quiz question order, or shuffle a deck. If you call nextInt() repeatedly, you can get duplicates. To guarantee uniqueness, you must either track what’s been generated or generate a shuffled range and take the first N values.
Core Java Random Classes
Java offers three main random number generators, each with different strengths:
java.util.Random– the classic, thread-safe (but with some contention), good for most non-security uses.java.util.concurrent.ThreadLocalRandom– faster in multi-threaded code because each thread has its own generator; you don’t instantiate it, you callThreadLocalRandom.current().java.security.SecureRandom– cryptographically strong, for passwords, tokens, or anything security-related. Slower but unpredictable.
For a simple random integer between 1 and 100 inclusive, use:
int num = ThreadLocalRandom.current().nextInt(1, 101); // 1 to 100
Note that nextInt(origin, bound) includes the origin and excludes the bound. If you want 0–99, use nextInt(100).
Generating a Single Unique Number
If you only need one random number, just call the method. There’s no uniqueness concern. However, if you need to ensure that number hasn’t been used before in a session (like a ticket ID), store already-used numbers in a HashSet<Integer> and loop until you find a new one:
Set<Integer> used = new HashSet<>();
Random rand = new Random();
int next;
do {
next = rand.nextInt(1000); // 0-999
} while (!used.add(next)); // add returns false if already present
This works, but if you need many numbers, it gets slower as the set fills up. A better approach for a known range is to shuffle.
Generating a List of Unique Numbers (Shuffle Method)
When you need, say, 5 unique numbers from 1 to 50, the most efficient and clean way is to create a list of all possible numbers, shuffle it, and take the first few:
List<Integer> numbers = new ArrayList<>();
for (int i = 1; i <= 50; i++) numbers.add(i);
Collections.shuffle(numbers);
List<Integer> uniqueFive = numbers.subList(0, 5); // 5 unique numbers
This guarantees no repeats and runs in O(n) time. It’s perfect for lotteries, random sampling without replacement, or shuffling a deck. The downside is memory usage if the range is huge (like 1 to 1 billion), but for typical ranges it’s fine.
Using Streams for Unique Random Numbers
Java 8+ streams offer a concise way to generate a stream of random numbers, but they don’t guarantee uniqueness by themselves. You can combine with distinct() and limit():
List<Integer> uniqueRandoms = new Random()
.ints(1, 100) // stream of ints from 1 to 99
.distinct()
.limit(10)
.boxed()
.collect(Collectors.toList());
This works, but be careful: if you ask for more numbers than the range allows (e.g., 100 distinct from 1–99), the stream will hang forever. Also, distinct() on a random stream may be slow if the range is small relative to the limit. For small ranges, shuffle is better.
Common Pitfalls and Mistakes
- Using
Math.random()– it returns a double between 0.0 and 1.0, and you have to multiply and cast to int, which is error-prone. Prefer the dedicated classes. - Forgetting the bound is exclusive –
nextInt(10)gives 0–9, not 1–10. This is the #1 off-by-one error. - Creating a new
Randomobject every call – if you create it in a tight loop, you might get the same seed on some systems (especially in older Java versions). Create one instance and reuse it. - Using
SecureRandomfor non-security – it’s slower, so don’t use it for a game dice roll unless you need unpredictability. - Not handling the “impossible” case – if you ask for more unique numbers than the range, you’ll get an infinite loop or an exception. Always check that your limit ≤ range size.
Performance and Thread-Safety Considerations
In single-threaded code, java.util.Random is fine. In multi-threaded applications, ThreadLocalRandom avoids contention because each thread has its own generator. SecureRandom is thread-safe but may block on entropy gathering. For shuffling, Collections.shuffle() uses a Random instance you can pass in—use ThreadLocalRandom.current() if you’re in a concurrent context, but note that shuffle is not thread-safe on the list itself, so synchronize externally if needed.
Alternatives: UUID and Other Unique Identifiers
If you don’t need numeric randomness but just a unique identifier, java.util.UUID.randomUUID() generates a 128-bit value that is practically unique across space and time. It returns a string like 550e8400-e29b-41d4-a716-446655440000. This is ideal for database keys, session IDs, or file names. However, UUIDs are not sequential and not suitable for sorting or indexing as numbers. For sequential unique numbers, you’d use an auto-increment database column or an AtomicInteger.
Frequently Asked Questions
How do I generate a random number between 1 and 100 in Java?
Use ThreadLocalRandom.current().nextInt(1, 101) or new Random().nextInt(100) + 1. The first is inclusive of 1 and exclusive of 101, so it gives 1–100. The second gives 0–99 then adds 1.
What’s the difference between Random and SecureRandom?
Random uses a linear congruential formula, which is fast but predictable if you know the seed. SecureRandom uses a cryptographically strong algorithm (like SHA1PRNG or native entropy), making it suitable for security-sensitive uses like generating passwords or tokens. It’s slower but unpredictable.
Can I get a random unique number without using a Set?
Yes, if you shuffle a list of all possible numbers and pick the first few, you don’t need a Set. Or if you generate a range and use Collections.shuffle(), that’s the standard approach. For a single number, uniqueness is irrelevant.
Why does my random number repeat when I run the program again?
Because the default seed for Random is based on the current time in nanoseconds, but if you create a new Random object with the same seed (e.g., new Random(42)), it will produce the same sequence. For different sequences each run, use the no-arg constructor or ThreadLocalRandom.
Is there a built-in method to generate a unique random number directly?
No, Java doesn’t have a single method that returns a unique random number because uniqueness only makes sense in context. You must combine random generation with a data structure (Set) or a shuffle. The closest is UUID.randomUUID() for unique identifiers, but that’s not a numeric random number.
How do I generate a random unique number in a range without duplicates in Java 8?
Use new Random().ints(min, max).distinct().limit(count).toArray(), but ensure count ≤ (max-min). For example, new Random().ints(1, 50).distinct().limit(5).toArray() gives 5 unique numbers from 1 to 49. For larger ranges, shuffle is more efficient.
Related
- How to Enter Data in RStudio: A Step-by-Step Guide
- Generate 2 Random Numbers: How to Do It
- Windows Shortcut Keys: The Complete List
Try it: the Formula Explainer: paste any formula and see each function and reference in plain English.
More in Formulas & functions
- Calculate Age in Excel From DD/MM/YYYY With a FormulaTo calculate someone’s age in Excel from a DD/MM/YYYY birth date, enter the birth date as a real…
- INDIRECT in Excel: How to Drag Formulas to New CellsIf you want an INDIRECT formula to follow different cells as you drag it, build its address from…
- Extract Text From a Cell in Excel With Simple FormulasTo extract part of a cell’s text in Excel, use a formula that matches what you need: for…
- Excel Formula for Age From DOB: Years, Months, and DaysTo calculate age in completed years from a date of birth in cell A2, use =DATEDIF(A2,TODAY(),"Y"). It compares…
- Excel COUNTIF: Find Text From a ListTo count cells that contain any text from a list in Excel for Microsoft 365, use =SUM(COUNTIF(A2:A10,"*"&C2:C4&"*")), where…
- Excel XLOOKUP With Multiple Criteria: Formulas & TipsTo use XLOOKUP with multiple criteria in Excel, multiply the criteria tests to require every condition to be…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.