Java Program to generate random numbers with no duplicates

Java 8Object Oriented ProgrammingProgramming

For random numbers in Java, create a Random class object −

Random randNum = new Random();

Now, create a HashSet to get only the unique elements i.e. no duplicates −

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

Generate random numbers with Random class nextInt −

while (set.size() < 5) {
   set.add(randNum.nextInt(5)+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() < 5) {
         set.add(randNum.nextInt(5)+1);
      }
      System.out.println("Random numbers with no duplicates = "+set);
   }
}

Output

Random numbers with no duplicates = [2, 4, 1, 3, 5]
raja
Published on 26-Apr-2019 10:12:21
Advertisements