Languages
[Edit]
EN

Java - generate random long in range

10 points
Created by:
Root-ssh
174740

1. ThreadLocalRandom - random long between min and max

public static long nextLongBetween(long min, long max) {
    return ThreadLocalRandom.current().nextLong(min, max);
}

Example:

System.out.println(nextLongBetween(1L, 100L)); // 88
System.out.println(nextLongBetween(500L, 1000L)); // 590
System.out.println(nextLongBetween(-100L, -5L)); // -7


2. Math.random() - random long between min and max

public static long nextLongBetween2(long min, long max) {
   return (long) (Math.random() * ((max - min) + 1)) + min;
}

Example:

System.out.println(nextLongBetween2(1L, 100L)); // 48
System.out.println(nextLongBetween2(500L, 1000L)); // 689
System.out.println(nextLongBetween2(-100L, -5L)); // -71


3. Random and LongStream - random long between min and max

public static long nextLongBetween3(long min, long max) {
    // java 8
    return new Random().longs(min, (max + 1)).limit(1).findFirst().getAsLong();
}

Example:

System.out.println(nextLongBetween3(1L, 100L)); // 58
System.out.println(nextLongBetween3(500L, 1000L)); // 702
System.out.println(nextLongBetween3(-100L, -5L)); // -15


References

ThreadLocalRandom - Java docs
Math - Java docs
Random - Java docs
LongStream - Java docs

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Java - random numbers

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join