List of Topics:
Location Research Breakthrough Possible @S-Logix pro@slogix.in

Office Address

Social List

How to Generate Random Number in Java Without Duplicates ?

Generate Random Number in Java Without Duplicates

Condition for Generating Random Number in Java Without Duplicates

  • Description:
    Generating random numbers without duplicates in Java can be achieved by using a Set to store the numbers, ensuring that only unique values are kept. A HashSet is commonly used because it automatically handles duplicates by not allowing the same number to be added more than once. A Random object or ThreadLocalRandom can be used to generate random numbers within a specified range. The process involves generating random numbers and checking if they already exist in the set before adding them. If the number is not in the set, it is added; if it already exists, another number is generated. This continues until the desired number of unique random numbers is generated. This approach is efficient and guarantees that all numbers in the set will be unique.
Sample Code
  • package JavaSamples;
    import java.util.HashSet;
    import java.util.Random;
    public class RandomNumber extends javax.swing.JFrame {
    public RandomNumber() {
    initComponents();
    }
    @SuppressWarnings("unchecked")
    //
    private void initComponents() {
    jLabel1 = new javax.swing.JLabel();
    jLabel2 = new javax.swing.JLabel();
    jTextField1 = new javax.swing.JTextField();
    jButton1 = new javax.swing.JButton();
    jScrollPane1 = new javax.swing.JScrollPane();
    jTextArea1 = new javax.swing.JTextArea();
    jLabel3 = new javax.swing.JLabel();
    jTextField2 = new javax.swing.JTextField();
    setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
    jLabel1.setText("Random Number Generator");
    jLabel2.setText("Count :");
    jTextField1.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jTextField1ActionPerformed(evt);
    }
    });
    jButton1.setText("Generate");
    jButton1.addActionListener(new java.awt.event.ActionListener() {
    public void actionPerformed(java.awt.event.ActionEvent evt) {
    jButton1ActionPerformed(evt);
    }
    });
    jTextArea1.setColumns(20);
    jTextArea1.setRows(5);
    jScrollPane1.setViewportView(jTextArea1);
    jLabel3.setText("Range :");
    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addGap(89, 89, 89)
    .addComponent(jButton1))
    .addGroup(layout.createSequentialGroup()
    .addGap(52, 52, 52)
    .addComponent(jScrollPane1,
    javax.swing.GroupLayout.PREFERRED_SIZE,
    javax.swing.GroupLayout.DEFAULT_SIZE,
    javax.swing.GroupLayout.PREFERRED_SIZE))
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
    .addGroup(layout.createSequentialGroup()
    .addGap(20, 20, 20)
    .addComponent(jLabel2)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE,46,
    javax.swing.GroupLayout.PREFERRED_SIZE)
    .addGap(48, 48, 48)
    .addComponent(jLabel3)
    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE,49,
    javax.swing.GroupLayout.PREFERRED_SIZE))
    .addGroup(javax.swing.GroupLayout.Alignment.LEADING,
    layout.createSequentialGroup()
    .addGap(88, 88, 88)
    .addComponent(jLabel1))))
    .addContainerGap(61, Short.MAX_VALUE))
    );
    layout.setVerticalGroup(
    layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
    .addGroup(layout.createSequentialGroup()
    .addGap(33, 33, 33)
    .addComponent(jLabel1)
    .addGap(22, 22, 22)
    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
    .addComponent(jLabel2)
    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE,
    javax.swing.GroupLayout.DEFAULT_SIZE,
    javax.swing.GroupLayout.PREFERRED_SIZE)
    .addComponent(jLabel3)
    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE,
    javax.swing.GroupLayout.DEFAULT_SIZE,
    javax.swing.GroupLayout.PREFERRED_SIZE))
    .addGap(26, 26, 26)
    .addComponent(jButton1)
    .addGap(18, 18, 18)
    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE,
    126, javax.swing.GroupLayout.PREFERRED_SIZE)
    .addContainerGap(45, Short.MAX_VALUE))
    );
    pack();
    }//

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
    int count = Integer.parseInt(jTextField1.getText());
    int range = Integer.parseInt(jTextField2.getText());
    HashSet uniqueNumbers = new HashSet<>();
    Random random = new Random();
    jTextArea1.setText("");
    while (uniqueNumbers.size() < count) {
    uniqueNumbers.add(random.nextInt(range));
    }
    uniqueNumbers.stream().forEach((num) -> {
    jTextArea1.append(num + "\n");
    });
    }
    private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {
    }
    public static void main(String args[]) {
    java.awt.EventQueue.invokeLater(() -> {
    new RandomNumber().setVisible(true);
    });
    }
    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    // End of variables declaration
    }
ScreenShots
  • The user creates the GUI for creating the random number generator.
    Generate Random Number in Java Without Duplicates1
  • The user generates a random number between 20 and 5 by counting.
    Generate Random Number in Java Without Duplicates2
  • To click the generate button it automatically generate the random numbers.
    Generate Random Number in Java Without Duplicates3