- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to generate random values that won’t repeat in Java
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
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]
Advertisements