Languages
[Edit]
EN

Java - generate random long in range

10 points
Created by:
Root-ssh
6665

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

Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.