Top community members
All Wiki Articles Create Wiki Article

Welcome to Dirask IT community! ❤ 💻
We are community of people that helps each other.

If you think you have some skills to help others

help someone and become a part of our community - List Q & A

Java - generate unique random numbers

0 contributions
3 points

There is couple of ways to generate unique random numbers in java.

1. List with Collections.shuffle

List<Integer> list = new ArrayList<>();
for (int i = 1; i <= 10; i++) {
	list.add(i);
}
Collections.shuffle(list);

// [8, 9, 7, 2, 10, 5, 3, 6, 1, 4]
System.out.println(list);
Collections.shuffle(list) - java docs:
Randomly permutes the specified list using a default source of randomness. 
All permutations occur with approximately equal likelihood.


2. HashSet with random numbers between 1 and 20

Set<Integer> unique = new HashSet<>();

while (unique.size() != 10) {
	int randInt = ThreadLocalRandom.current().nextInt(1, 20);
	unique.add(randInt);
}

// [16, 1, 17, 18, 6, 9, 10, 13, 14, 15]
System.out.println(unique.toString());

We generate new unique numbers until HashSet has expected size.

3. Java 8 - Random + IntStream + distinct + limit

List<Integer> list = ThreadLocalRandom.current()
        .ints(1, 20)
        .boxed()
        .distinct()
        .limit(10)
        .collect(Collectors.toList());

// [3, 17, 9, 15, 4, 19, 18, 16, 14, 8]
System.out.println(list);

ints(1, 20) - generate random numbers between 1 and 20
limit(10) - size of our output collection will be 10

0 contributions

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more