IntStream 生成长度为8的数组值为0的数组
时间: 2024-02-03 22:14:55 浏览: 12
你可以使用以下代码生成长度为8的值为0的数组:
```
int[] array = IntStream.generate(() -> 0).limit(8).toArray();
```
这里使用了 `IntStream.generate()` 方法来生成一个无限长度的 `IntStream`,并使用 lambda 表达式 `() -> 0` 来生成每个元素的值为0。然后使用 `limit()` 方法来限制长度为8,并使用 `toArray()` 方法将 `IntStream` 转换为 `int` 数组。
相关问题
IntStream 生成长度为8的数组
可以使用 `IntStream` 的 `generate` 方法生成一个长度为8的随机数组,代码如下:
```java
import java.util.Random;
import java.util.stream.IntStream;
public class Main {
public static void main(String[] args) {
int[] arr = IntStream.generate(() -> new Random().nextInt()).limit(8).toArray();
System.out.println(Arrays.toString(arr));
}
}
```
该程序运行时会生成一个长度为8的随机整数数组,并输出数组内容。
int数组转换为泛型数组
可以使用Java中的Arrays类的静态方法toArray(T[] a, IntFunction<T[]> generator)来将int数组转换为泛型数组。具体实现可以参考以下代码:
int[] intArray = {1, 2, 3, 4, 5};
Integer[] genericArray = Arrays.stream(intArray).boxed().toArray(Integer[]::new);
这里使用了Java 8中的Stream API将int数组转换为IntStream,再使用boxed()方法将IntStream转换为Stream<Integer>,最后使用toArray(Integer[]::new)将Stream<Integer>转换为Integer数组。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)