Java Program to generate n distinct random numbers

Java 8Object Oriented ProgrammingProgramming

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]
raja
Published on 26-Apr-2019 06:23:59
Advertisements