Generate Random Numbers in a range using Java 8

Carvia Tech | December 27, 2017 | 1 min read | 208 views | Java 8


Java 8 Random.ints

In Java 8, new methods are added in java.util.Random

This Random.ints(int origin, int bound) or Random.ints(int min, int max) generates a random integer from origin (inclusive) to bound (exclusive).

3.1 Code snippet.
private static int getRandomNumberInRange(int min, int max) {

	Random r = new Random();
	return r.ints(min, (max + 1)).findFirst().getAsInt();

}

Top articles in this category:
  1. Given a collection of 1 million integers, all ranging between 1 to 9, sort them in Big O(n) time
  2. Secure OTP generation in Java
  3. Factorial of a large number in Java BigInteger
  4. Java 8 Parallel Stream custom ThreadPool
  5. Diamond Problem of Inheritance in Java 8
  6. can we write a java method that swaps two integers
  7. Find missing numbers in 4 billion unique numbers with 50MB RAM

Find more on this topic:

Recommended books for interview preparation:
Buy interview books

Java & Microservices interview refresher for experienced developers.


This website uses cookies to ensure you get the best experience on our website. more info