Top community members
All Wiki Articles Create Wiki Article

Welcome to Dirask IT community! ❤ 💻
We are community that shares solutions with each other.

If you think you have something to add here.

you are welcome with your fresh ideas - List Articles

Java - generate random long in range

0 contributions
10 points

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

0 contributions

Checkout latest Findings & News:

Checkout latest questions:

Checkout latest wiki articles:

Hey 👋
Would you like to know what we do?
  • Dirask is IT community, where we share coding knowledge and help each other to solve coding problems.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.
Read more