Java Program to generate n distinct random numbers


For distinct numbers, use Set, since all its implementations remove duplicates −

Set<Integer>set = new LinkedHashSet<Integer>();

Now, create a Random class object −

Random randNum = new Random();

Generate 10 distinct random numbers now with nextInt of the Random class −

while (set.size() < 10) {
   set.add(randNum.nextInt(10)+1);
}

Example

import java.util.LinkedHashSet;
import java.util.Random;
import java.util.Set;
public class Demo {
   public static void main(final String[] args) throws Exception {
      Random randNum = new Random();
      Set<Integer>set = new LinkedHashSet<Integer>();
      while (set.size() < 10) {
         set.add(randNum.nextInt(10)+1);
      }
      System.out.println("Distinct random numbers = "+set);
   }
}

Output

Distinct random numbers = [4, 6, 9, 1, 5, 2, 8, 7, 10, 3]

Updated on: 30-Jul-2019

600 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements