SoFunction
Updated on 2025-04-14

Examples of four methods to generate non-repetitive random numbers in Java

summary:

In Java development, generating non-repetitive random numbers is a common requirement, such as lottery, random sampling and other scenarios. This article provides four efficient implementation solutions, covering scenarios with different scopes and data volumes, and is accompanied by complete code examples.

1. Requirement scenario analysis

The core problem of generating non-repetitive random numbers is "how to avoid duplication". Depending on the different ranges and number of generated, we need to choose different strategies:

-Small range and full coverage (such as 1~100): Suitable for the order of disruption after pre-generating.

- Large range but small number (such as 1~100,000 take 10): Suitable for dynamic generation and deduplication.

- Dynamic generation of medium range (such as 1~1000 to take 100): suitable for gradually removing selected values.

2. Specific implementation methods

Method 1: Use `` to disrupt the order

Applicable scenarios: generate non-repetitive sequences of all values ​​within a fixed range (such as shuffling algorithm).

import ;
import ;
import ;

public class ShuffleDemo {
    public static void main(String[] args) {
        int min = 1, max = 100;
        List<Integer> numbers = new ArrayList<>();
        for (int i = min; i <= max; i++) {
            (i);
        }
        (numbers); // Key: Random disruption order        
        // Get the first 10 unrepeated values        ().limit(10).forEach(::println);
    }
}

Advantages: Time complexity O(n), extremely high efficiency.

Disadvantages: All values ​​need to be pre-generated, and the memory usage is high.

Method 2: Deduplication through `Set`

Applicable scenarios: generate a small number of random numbers from a large range (such as taking 10 from 1~100,000).

import ;
import ;
import ;

public class SetDemo {
    public static void main(String[] args) {
        int min = 1, max = 100_000, count = 10;
        Set<Integer> uniqueNumbers = new HashSet<>();
        Random random = new Random();

        while (() < count) {
            int num = (max - min + 1) + min;
            (num); // Set automatically deduplicates        }

        (::println);
    }
}

Advantages: Low memory footprint.

Disadvantages: Performance drops sharply when the number of generations is close to the upper limit of the range.

Method 3: Dynamically remove selected values

Applicable scenarios: Dynamic generation in medium range (such as taking 500 from 1~1000).

import ;
import ;
import ;

public class PoolDemo {
    public static void main(String[] args) {
        int min = 1, max = 1000, count = 10;
        List<Integer> pool = new ArrayList<>();
        for (int i = min; i <= max; i++) {
            (i);
        }

        Random random = new Random();
        for (int i = 0; i < count; i++) {
            int index = (());
            int num = (index); // Remove selected values            (num);
        }
    }
}

Advantages: Avoid repeated collision problems.

Disadvantages: Frequent operation of List may lead to performance degradation.

Method 4: Java 8 Stream API (concise writing method)

Applicable scenarios: Quickly generate a small number of non-repetitive values.

import ;
import ;

public class StreamDemo {
    public static void main(String[] args) {
        int min = 1, max = 100, count = 10;
        Random random = new Random();

        (() -> (max - min + 1) + min)
                .distinct()     // Deduplication                .limit(count)   // Limit quantity                .forEach(::println);
    }
}

Advantages: The code is concise and suitable for functional programming.

Disadvantages: Not suitable for scenarios where the number of generated is close to the upper limit of the range.

3. Performance and precautions

1. The relationship between range and quantity**: `count ≤ (max - min + 1)` must be met, otherwise the code will fall into a dead loop.

2. Thread Safety: It is recommended to use `ThreadLocalRandom` in a multi-threaded environment.

3. Performance comparison:

- Optimal scenario: `` > Dynamic removal > Set > Stream

- Worst scenario: (such as generating 999/1000 values): Dynamic removal > `` > Set > Stream

4. Summary

| Method

| ``  | Small-scale full coverage                                        | ⭐⭐⭐⭐ |
| `Set`Deduplication                                    |
| Dynamic removal                                |
| Stream API                                    | ⭐⭐      |

It is recommended to choose the most appropriate method according to actual needs to avoid performance problems caused by improper algorithm selection.

This is the end of this article about the four methods of generating non-repeating random numbers in Java. For more related Java methods, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!