Languages
[Edit]
EN

Java - generate random long in range

10 points
Created by:
Root-ssh
68440

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

Java - random numbers

Native Advertising
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join