M
M
Maxim Siomin2021-08-19 19:05:47
Java
Maxim Siomin, 2021-08-19 19:05:47

How to get a long value from a specific SecureRandom Java range?

import java.security.SecureRandom

public class RandomUtil {
    
    long nextLong(long min, long max) {
        SecureRandom secureRandom = new SecureRandom();
        // как вернуть число из диапазона?
    }
}

In the built-in Kotlin random, this is done simply:
import kotlin.random.Random

fun nextLong(min: Long, max: Long): Long = Random.nextLong(min, max + 1)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Gornostaev, 2021-08-19
@MaxSiominDev

long min = 42;
long max = 1488;

SecureRandom secureRandom = new SecureRandom();
long value = secureRandom.longs(1, min, max)
    .findFirst()
    .orElseThrow(() -> new RuntimeException("Не удалось получить случайное число"));

or
long value = secureRandom.longs(1, min, max).reduce(0, (a, b) -> b);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question