Languages
[Edit]
EN

Java - generate unique random numbers

3 points
Created by:
AnnLen
1777

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

Java - random numbers

Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.