public static int[] convertListToArray(List<Integer> listResult) {
int[] result = new int[listResult.size()];
int i= 0;
for (int num : listResult) {
result[i++] = num;
}
return result;
}
有没有一种有效的方法将List转换为数组而不显式迭代List? 也许可以通过使用以下方法来实现:
Arrays.copyOf(int [] origin , int newLength );
System.arraycopy(Object src, int srcPos,
Object dest, int destPos,
int length);
我知道有一个解决方案here。但是,我特别感兴趣的是将List<Integer>
转换为int[]
答案 0 :(得分:11)
如果效率是您最关心的问题,我认为您可以使用您的解决方案,并通过在listResult上使用索引for循环(如果它是RandomAccess
)来提高效率。但是这会使代码的可读性降低,并且您必须根据用例对其进行基准测试,以确定它是否更有效。
public static int[] convertListToArray(List<Integer> listResult) {
int size = listResult.size();
int[] result = new int[size];
if (listResult instanceof RandomAccess)
{
for (int i = 0; i < size; i++)
{
result[i] = listResult.get(i);
}
}
else
{
int i = 0;
for (int num : listResult) {
result[i++] = num;
}
}
return result;
}
如果您使用Java 8并希望编写更少的代码,则可以使用Streams库。
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
int[] array = list.stream().mapToInt(i -> i).toArray();
如果您愿意使用第三方库,可以按照以下方式Eclipse Collections进行操作。
MutableList<Integer> list = Lists.mutable.with(1, 2, 3, 4, 5);
int[] array = list.collectInt(i -> i).toArray();
以下是稍微多一点的代码,但是我可以使用Eclipse Collections来提供最有效的解决方案。
MutableList<Integer> list = Lists.mutable.with(1, 2, 3, 4, 5);
int[] array = new int[list.size()];
list.forEachWithIndex((each, index) -> array[index] = each);
如果需要使用java.util.List
接口,可以在Eclipse Collections中使用ListIterate实用程序类。
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
int[] array = new int[list.size()];
ListIterate.forEachWithIndex(list, (each, index) -> array[index] = each);
ListIterate
实用程序将为RandomAccess
列表和非RandomAccess
列表使用不同的迭代代码。
最有效的方法是将Eclipse集合中的List<Integer>
更改为MutableIntList
或另一个支持原始集合的库。
注意:我是Eclipse Collections的提交者。
答案 1 :(得分:7)
鉴于需要从Integer
转换为int
,如果我假设您在谈论运行时效率,我认为您不会找到比您拥有的更有效的东西
您可能首先找到转换为Integer[]
,然后循环可能更有效(下方),但您也可能不。您必须在特定情况下对其进行测试并查看。
以下是这个例子:
int size = listResult.size();
int[] result = new int[size];
Integer[] temp = listResult.toArray(new Integer[size]);
for (int n = 0; n < size; ++n) {
result[n] = temp[n];
}
答案 2 :(得分:4)
在Java 8中:
int[] anArray = list.stream()
.filter(Objects::nonNull)
.mapToInt(Integer::intValue)
.toArray();
答案 3 :(得分:0)
有一种有效的方法可以实现此Java。但是,这可能会为有人创建通用功能(取决于需求)打开空间。
就像我写的这个示例一样,我建议您对程序的特定知识也这样做。
// Generic function to convert set to list
public static <T> ArrayList<T> convertSetToList(Set<T> set)
{
// create an empty list
ArrayList<T> list = new ArrayList<>();
// push each element in the set into the list
for (T t : set)
list.add(t);
// return the list
return list;
}