![](/img/trans.png)
[英]Java - How to generate a 2D Array with random ints, where the grid size is N*N (User Input)?
[英]How to generate random array of ints using Stream API Java 8?
我正在尝试使用 Java 8 中的新 Stream API 生成随机整数数组。但我还没有清楚地理解这个 API。 所以我需要帮助。 这是我的代码。
Random random = new Random();
IntStream intStream = random.ints(low, high);
int[] array = intStream.limit(limit) // Limit amount of elements
.boxed() // cast to Integer
.toArray();
但是此代码返回对象数组。 它有什么问题?
如果您想要原始int
值,请不要调用IntStream::boxed
因为它会通过boxing生成Integer
对象。
只需使用返回IntStream
Random::ints
:
int[] array = new Random().ints(size, lowBound, highBound).toArray();
没有理由boxed()
。 只需将Stream
作为int[]
接收。
int[] array = intStream.limit(limit).toArray();
生成 0 到 350 范围内的随机数,将结果限制为 10,并收集为列表。 后来它可以被类型转换。
但是,对返回的 List 的类型、可变性、可序列化性或线程安全性没有任何保证。
List<Object> numbers = new Random().ints(0,350).limit(10).boxed().collect(Collectors.toList());
并获得 int 使用的数组
int[] numbers = new Random().ints(0,350).limit(10).toArray();
ThreadLocalRandom // A random number generator isolated to the current thread.
.current() // Returns the current thread's `ThreadLocalRandom` object.
.ints( low , high ) // Pass the "origin" (inclusive) and "bound" (exclusive).
.limit( 100 ) // How many elements (integers) do you want in your stream?
.toArray() // Convert the stream of `int` values into an array `int[]`.
ThreadLocalRandom
您可以使用ThreadLocalRandom
。
ints
方法在您指定的范围内生成一个IntStream
。 请注意,low 是包容性的,而 high 是不包括的。 如果你想包括你的高数,只需在调用ints
方法时添加一个。
int[] randInts = ThreadLocalRandom.current().ints( low , high ).limit(100).toArray();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.