EN
Java - get random long
10
points
1. Generate random long with ThreadLocalRandom
public static long nextLong() {
return ThreadLocalRandom.current().nextLong();
}
Example:
System.out.println(nextLong()); // 387012672104004517
System.out.println(nextLong()); // 6852957493264943261
System.out.println(nextLong()); // -71063557433901021
2. Generate random long with Random
public static long nextLong2() {
return new Random().nextLong();
}
Example:
System.out.println(nextLong2()); // 1210711763149946015
System.out.println(nextLong2()); // -7418942686528922245
System.out.println(nextLong2()); // -453231838162786783
3. Generate random long with Random
and LongStream
public static long nextLong3() {
// java 8
return new Random().longs().limit(1).findFirst().getAsLong();
}
Example:
System.out.println(nextLong3()); // 8162070174534088347
System.out.println(nextLong3()); // 1459269772671493893
System.out.println(nextLong3()); // 433964390590900751
If we want to generate random long in range look into post:
https://dirask.com/q/zjM8wp
References
ThreadLocalRandom - Java docs
Random - Java docs
LongStream - Java docs