How to generate Random Numbers in Java
In this tutorial, we’ll learn how to generate a random number, generate a random array or list, get a random element from an array or list, and shuffle the list elements.
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;
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 Integer within a specific Range
Let’s create a method that uses Random
class to generate a random Integer within the specific range of min and max values inclusive.
public static int generateRandomInt(int min, int max){
return min + new Random().nextInt(max-min+1);
}
The method returns a random integer every time you run it.
System.out.println(generateRandomInt(1, 5));
// Prints random integer "4"
// Prints random integer "1"
// Prints random integer "5"
Generate Array of Random Numbers within a specific Range
Let’s create a method that uses Random
class and Java Streams to generate an Array of random numbers of a given size and all elements of that Array should be in the given range of min and max values inclusive.
public static int[] generateRandomArray(int size, int min, int max) {
return IntStream
.generate(() -> min + new Random().nextInt(max - min + 1))
.limit(size)
.toArray();
}
Let’s use the above method to generate an Array of 5 random numbers between 0 to 9 inclusive. The method will generate a random array every time you run it.
System.out.println(Arrays.toString(generateRandomArray(5, 0, 9)));
// Prints random array "[1, 9, 7, 0, 4]"
// Prints random array "[7, 1, 2, 8, 5]"
// Prints random array "[5, 7, 5, 2, 3]"
Generate List of Random Numbers within a specific Range
Let’s create a method using Random
class and Java Streams to generate a List of random numbers of a given size and all elements in that List should be in the given range of min and max values inclusive.
public static List<Integer> generateRandomList(int size, int min, int max) {
return IntStream
.generate(() -> min + new Random().nextInt(max-min+1))
.limit(size)
.boxed()
.collect(Collectors.toList());
}
Let’s use the above method to generate a List of 5 random numbers between 0 to 9 inclusive. The method will generate a random list every time you run it.
System.out.println(generateRandomList(5, 0, 9));
// Prints random list "[3, 5, 7, 2, 4]"
// Prints random list "[8, 7, 7, 5, 4]"
// Prints random list "[5, 9, 8, 7, 5]"
Get Random Element from an Array
You can get a random element from an Array of elements by generating a random index within the length range of the Array.
Let’s run the below code snippet, which prints the random user from the Array every time:-
String[] users = new String[] { "Adam", "Bill", "Charlie", "David", "Eva", "Fang", "George", "Harry", "Ivy", "Jack" };
Random random = new Random();
System.out.println(users[random.nextInt(users.length)]);
// Prints random user "Eva"
// Prints random user "Charlie"
// Prints random user "Fang"
Get Random Element from a List
You can get a random element from a List of elements by generating a random index within the size range of the List.
Let’s run the below code snippet, which prints the random user from the list every time:-
List<String> users = List.of("Adam", "Bill", "Charlie", "David", "Eva", "Fang", "George", "Harry", "Ivy", "Jack");
Random random = new Random();
System.out.println(users.get(random.nextInt(users.size())));
// Prints random user "David"
// Prints random user "George"
// Prints random user "Charlie"
Shuffle Elements in a 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 the random sequence:-
List<String> userList = List.of("Adam", "Bill", "Charlie", "David", "Eva", "Fang", "George", "Harry", "Ivy", "Jack");
Collections.shuffle(userList);
System.out.println(userList);
// Prints random list everytime "[Charlie, Bill, Harry, George, Jack, Ivy, Fang, Eva, David, Adam]"
Collections.shuffle(userList);
System.out.println(userList);
// Prints random list everytime "[Eva, Ivy, Fang, Jack, Harry, Bill, Charlie, George, David, Adam]"
Let’s return 5 random users from the given list of users:-
Collections.shuffle(userList);
List<String> fiveUsers = userList.subList(0, 5);
System.out.println(fiveUsers);
// Prints "[Eva, Bill, David, George, Fang]"