How to generate random values that won’t repeat in Java

Java 8Object Oriented ProgrammingProgramming

To generate random values that won’t repeat, use HashSet collection. Firstly, create a random object and HashSet −

Random randNum = new Random();
Set<Integer>s = new HashSet<Integer>();

Now, add random integers −

while (s.size() < 10) {
   s.add(randNum.nextInt());
}

Now, display the random numbers that are unique −

List<Integer>list = new ArrayList<Integer>(s);
System.out.println(list);

Example

 Live Demo

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import java.util.Random;
import java.util.List;
public class Demo {
   public static void main(String[] args) {
      Random randNum = new Random();
      Set<Integer>s = new HashSet<Integer>();
      while (s.size() < 10) {
         s.add(randNum.nextInt());
      }
      System.out.println("Random numbers that aren't repeating...");
      List<Integer>list = new ArrayList<Integer>(s);
      System.out.println(list);
   }
}

Output

Random numbers that aren't repeating...
[-951684393, -2119833673, 1804429247, -1389537752, -1314261216, 575783898, 326063891, -1241554605, -613888875, -1698001241]

Let us see another example to get distinct random numbers that won’t repeat −

Random numbers that aren't repeating...
[1173054490, -613376175, -1947139369, -840397233, 931136232, 135129829, 1634496580, 13228721, 1929509800, 1205305181]
raja
Published on 23-Apr-2019 09:08:48
Advertisements