![](/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.