如何使用 Stream API Java 8 生成随机整数数组?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25793098/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to generate random array of ints using Stream API Java 8?
提问by
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. So I need help. Here is my code.
我正在尝试使用 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();
But this code returns array of objects. What is wrong with it?
但是此代码返回对象数组。它有什么问题?
采纳答案by Jean Logeart
If you want primitive int
values, do not call IntStream::boxed
as that produces Integer
objects by boxing.
如果您想要原始int
值,请不要调用IntStream::boxed
asInteger
通过boxing生成对象。
Simply use Random::ints
which returns an IntStream
:
只需使用Random::ints
它返回一个IntStream
:
int[] array = new Random().ints(size, lowBound, highBound).toArray();
回答by Sotirios Delimanolis
There's no reason to boxed()
. Just receive the Stream
as an int[]
.
没有理由boxed()
。只需Stream
将int[]
.
int[] array = intStream.limit(limit).toArray();
回答by zeronone
You can do it using ThreadLocalRandom
.
您可以使用ThreadLocalRandom
.
int[] randInts = ThreadLocalRandom.current().ints().limit(100).toArray();
回答by Lakshay Gupta
To generate random numbers from range 0 to 350, limiting the result to 10, and collect as a List. Later it could be typecasted.
生成 0 到 350 范围内的随机数,将结果限制为 10,并收集为列表。后来它可以被类型转换。
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();