Create a Unique List of Integers with Java

Create a List of Unique and Random Integers in Java

October 14, 2016


What to use:

ArrayList & Collections.shuffle()

The Code:

import java.util.ArrayList;
import java.util.Collections;

public class RandomNum
{
     public static void main(String[] args)
     {
          //set this to however many integers you need
          int numberOfIntegersNeeded = 10;

          //create a new ArrayList that holds Integers
          ArrayList randomIntsArray = new ArrayList<>();

          //loop through each index of the ArrayList and set that index to an integer
          for(int i = 0; i < numberOfIntegersNeeded; i++){
               randomIntsArray.add(i);
          }

          //Use the collections shuffle method to randomize the index order of the ArrayList
          Collections.shuffle(randomIntsArray);

          for(int m = 0; m < numberOfIntegersNeeded; m++){
               System.out.println(randomIntsArray.get(m));
          }
     }
}

A practical use: Randomize an Array of Color String Values.

import java.util.ArrayList;
import java.util.Collections;

public class RandomNum
{

     public static void main(String[] args)
     {
          //The magic number String colors and integer values
          int numberOfIntegersNeeded = 3;

          //An Integer ArrayList Initialized
          ArrayList randomIntsArray = new ArrayList<>();

          //Adding integer values in sequential order to new Integer Array
          for(int i = 0; i < numberOfIntegersNeeded; i++){
               randomIntsArray.add(i);
          }

          //Randomizing the Integer Array
          Collections.shuffle(randomIntsArray);

          //Initialize a new String Array with color values
          String [] colors = {"blue", "red", "white"};
          //Initialize a new String Array that will hold the randomized String colors
          String [] colorsMixedUp = new String [3];

          //Setting random color values to Random Strings Array
          for(int m = 0; m < numberOfIntegersNeeded; m++){
               //setting an integer variable to the designated
               //randomized number in the Random Number Array
               int h = randomIntsArray.get(m);
               //Setting a random color value to Random String Array
               colorsMixedUp[m] = colors[h];
          }

          //Write out values to see random colors
          for(int y = 0; y < numberOfIntegersNeeded; y++){
               System.out.println(colorsMixedUp[y]);
          }
     }

}