📜  将整数列表转换为整数数组的Java程序(1)

📅  最后修改于: 2023-12-03 15:25:19.901000             🧑  作者: Mango

将整数列表转换为整数数组的Java程序

在Java中,List和Array是两种不同的数据结构。在某些情况下,我们可能需要将List转换为Array,以便更方便地进行某些操作。本文将介绍如何将整数列表转换为整数数组的Java程序。

方法一:使用循环逐个添加

首先,我们可以使用for循环逐个遍历List中的元素,然后将它们添加到数组中。这种方法的代码如下所示:

List<Integer> integerList = new ArrayList<Integer>();
integerList.add(1);
integerList.add(2);
integerList.add(3);

int[] integerArray = new int[integerList.size()];
for (int i = 0; i < integerList.size(); i++) {
    integerArray[i] = integerList.get(i);
}

System.out.println(Arrays.toString(integerArray));    // [1, 2, 3]

这个程序中,首先我们创建了一个包含一些整数的List。然后,我们定义了一个整数数组,它的大小与List的大小相同。接下来,我们使用for循环逐个遍历List中的元素,并将它们添加到数组中。最后,我们打印出整数数组的值。

方法二:使用Java 8的Stream API

另一个方法是使用Java 8的Stream API。这种方法比较简洁,而且代码可读性更高。此外,它还使用了lambda表达式,这让代码更加优雅。这种方法的代码如下所示:

List<Integer> integerList = new ArrayList<Integer>();
integerList.add(1);
integerList.add(2);
integerList.add(3);

int[] integerArray = integerList.stream().mapToInt(i -> i).toArray();

System.out.println(Arrays.toString(integerArray));    // [1, 2, 3]

这个程序中,我们首先创建了一个包含一些整数的List。然后,我们使用stream()方法将其转换为Stream,然后使用mapToInt()方法将Stream中的每个元素映射为其相应的int值。最后,我们使用toArray()方法将Stream中的所有元素收集到一个整数数组中。

总结

综上所述,我们介绍了两种将整数列表转换为整数数组的Java程序。第一种方法使用for循环逐个添加,而第二种方法则使用Java 8的Stream API。这两种方法都可行,选择哪种方法取决于个人喜好和情况。