Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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]
Advertisements