简体   繁体   English

如何使用 Stream API Java 8 生成随机整数数组?

[英]How to generate random array of ints using Stream API Java 8?

I am trying to generate random array of integers using new Stream API in Java 8. But I haven't understood this API clearly yet.我正在尝试使用 Java 8 中的新 Stream API 生成随机整数数组。但我还没有清楚地理解这个 API。 So I need help.所以我需要帮助。 Here is my code.这是我的代码。

Random random = new Random();
IntStream intStream = random.ints(low, high);
int[] array =  intStream.limit(limit) // Limit amount of elements
                                    .boxed() // cast to Integer
                                    .toArray();

But this code returns array of objects.但是此代码返回对象数组。 What is wrong with it?它有什么问题?

If you want primitive int values, do not call IntStream::boxed as that produces Integer objects by boxing .如果您想要原始int值,请不要调用IntStream::boxed因为它会通过boxing生成Integer对象。

Simply use Random::ints which returns an IntStream :只需使用返回IntStream Random::ints

int[] array = new Random().ints(size, lowBound, highBound).toArray();

There's no reason to boxed() .没有理由boxed() Just receive the Stream as an int[] .只需将Stream作为int[]接收。

int[] array = intStream.limit(limit).toArray();

To generate random numbers from range 0 to 350, limiting the result to 10, and collect as a List.生成 0 到 350 范围内的随机数,将结果限制为 10,并收集为列表。 Later it could be typecasted.后来它可以被类型转换。

However, There are no guarantees on the type, mutability, serializability, or thread-safety of the List returned.但是,对返回的 List 的类型、可变性、可序列化性或线程安全性没有任何保证。

List<Object> numbers =  new Random().ints(0,350).limit(10).boxed().collect(Collectors.toList());

and to get thearray of int use并获得 int 使用的数组

int[] numbers =  new Random().ints(0,350).limit(10).toArray();

tl;dr tl;博士

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

You can do it using ThreadLocalRandom .您可以使用ThreadLocalRandom

The ints method generates an IntStream within your specified bounds. ints方法在您指定的范围内生成一个IntStream Note the the low is inclusive while the high is exclusive .请注意,low 是包容性的,而 high 是不包括的 If you want to include your high number, just add one while calling the ints method.如果你想包括你的高数,只需在调用ints方法时添加一个。

int[] randInts = ThreadLocalRandom.current().ints( low , high ).limit(100).toArray();

See this code run live at IdeOne.com .查看此代码在 IdeOne.com 上实时运行

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM