Top community members
All Wiki Articles Create Wiki Article

Welcome to Dirask IT community! ❤ 💻
We are community of people that helps each other.

If you think you have some skills to help others

help someone and become a part of our community - List Q & A

Java - get random long

0 contributions
10 points

1. Generate random long with ThreadLocalRandom

public static long nextLong() {
    return ThreadLocalRandom.current().nextLong();


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();


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();


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:


ThreadLocalRandom - 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