Java Program to generate random numbers with no duplicates


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]

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 30-Jul-2019

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements