How to generate Random Numbers in Java



How to generate Random Numbers in Java | ninjasquad

In this tutorial, we’ll learn how to generate random number, generate random list, get random number from list, shuffle elements in list using Random Class in Java.

Generate Random Number

Java Random class is having many useful built-in methods for generating random numbers as follows:-

  • nextInt(): Returns a random int value within the range: -2,147,483,648<= value <= 2,147,483, 647
  • nextInt(int range): Returns a random int value within the range: 0 <= value < range
  • nextDouble(): Returns a random double value within the range: 0.0 <= value < 1.0
  • nextFloat(): Returns a random float value within the range: 0.0 <= value < 1.0
  • nextLong(): Returns a random long value.
import java.util.Random; //The import statement
class generateRandom {
  public static void main( String args[] ) {
    //Creating an object of Random class
    Random random = new Random();
    //Calling the nextInt() method
    System.out.println("A random int: " + random.nextInt());  
    //Calling the overloaded nextInt() method
    System.out.println("A random int from 0 to 49: "+ random.nextInt(50));
    //Calling the nextDouble() method
    System.out.println("A random double: "+ random.nextDouble()); 
    //Calling the nextFloat() method
    System.out.println("A random float: "+ random.nextFloat());
    //Calling the nextLong() method
    System.out.println("A random long: "+ random.nextLong());  
  }
}

Output

A random int: -1836807784 A random int from 0 to 49: 8 A random double: 0.8662629682535646 A random float: 0.47197896 A random long: -4184120388957206673

Generate Random Array

We can create our own method using Random class to generate an Array of random number in given size and range.

public int[] generateRandomArray(int size, int minValueInclusive, int maxValueExclusive) {
  int[] array = new int[size];
  Random random = new Random();
  for (int i = 0; i < size; i++) {
    array[i] = minValueInclusive + random.nextInt(maxValueExclusive-minValueInclusive);
  }
  return array;
}

We can further improve the method using streams:-

public int[] generateRandomArray(int size, int minValueInclusive, int maxValueExclusive) {
  return IntStream
    .generate(() -> minValueInclusive + new Random().nextInt(maxValueExclusive-minValueInclusive))
    .limit(size)
    .toArray();
}

Let’s generate 5 random numbers using this method:-

System.out.println("Array(5) of numbers between 0 to 99: " + Arrays.toString(generateRandomArray(5, 0, 100)));
//Prints Array(5) of numbers between 0 to 99: [20, 72, 4, 20, 7]

System.out.println("Array(5) of numbers between 100 to 199: " + Arrays.toString(generateRandomArray(5, 100, 200)));
//Prints Array(5) of numbers between 100 to 199: [175, 100, 181, 153, 182]

Generate Random List

Similar to Array, we can create our own method using Random class to generate List of random numbers in given size and range.

public List<Integer> generateRandomList(int size, int minValueInclusive, int maxValueExclusive) {
  return IntStream
    .generate(() -> minValueInclusive + new Random().nextInt(maxValueExclusive-minValueInclusive))
    .limit(size)
    .boxed()
    .collect(Collectors.toList());
}

Let’s generate 5 random numbers using this method:-

System.out.println("List(5) of numbers between 0 to 99: " + generateRandomList(5, 0, 100));
//Prints List(5) of numbers between 0 to 99: [6, 90, 5, 93, 16]

System.out.println("List(5) of numbers between 100 to 199: " + generateRandomList(5, 100, 200));
//Prints List(5) of numbers between 0 to 99: [192, 112, 150, 132, 144]

Get Random Element from Array

We can get random user from an Array of users in following way:-

String[] users = new String[] { "Adam", "Bill", "Charlie", "David", "Eva", "Fang", "George", "Harry", "Ivy", "Jack" };
Random random = new Random();
System.out.println("Get Random User: " + users[random.nextInt(users.length)]);
// Prints Get Random User: Eva

Get Random Element from List

Similar to Array, we can get random user from a list of users in following way:-

List<String> users = Arrays.asList("Adam", "Bill", "Charlie", "David", "Eva", "Fang", "George", "Harry", "Ivy", "Jack");
Random random = new Random();
System.out.println("Get Random User: " + users.get(random.nextInt(users.length)));
// Prints Get Random User: Harry

Shuffle Elements in List

Java Collections provide a built-in shuffle() method to shuffle the elements of a List.

Let’s shuffle the list of users and return users with random sequence:-

List<String> userList = Arrays.asList("Adam", "Bill", "Charlie", "David", "Eva", "Fang", "George", "Harry", "Ivy", "Jack");

Collections.shuffle(userList);
System.out.println(userList); 
// Prints [Charlie, Bill, Harry, George, Jack, Ivy, Fang, Eva, David, Adam]

Collections.shuffle(userList);
System.out.println(userList); 
// Prints [Eva, Ivy, Fang, Jack, Harry, Bill, Charlie, George, David, Adam]

Let’s return 5 random users from given list of users:-

Collections.shuffle(userList);
List<String> fiveUsers = userList.subList(0, 5);
System.out.println(fiveUsers);
// Prints [Eva, Bill, David, George, Fang]



Source: Internet

Leave a Comment

We are offering free coding tuts

X