Java 一种无需迭代即可将 List<Integer> 转换为 int[] ( array ) 的有效方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41520654/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 23:27:36  来源:igfitidea点击:

An efficient way to convert List<Integer> to int[] ( array ) without iteration

javaarrayslist

提问by Tim Florian

  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;
    }

Is there an efficient way to convert List to array without iterating List explicitly ? Maybe it is possible by using methods like:

有没有一种有效的方法可以在不显式迭代 List 的情况下将 List 转换为数组?也许可以使用以下方法:

Arrays.copyOf(int [] origin , int newLength );
System.arraycopy(Object src,  int  srcPos,
                                    Object dest, int destPos,
                                    int length);

I know that there is a solution described here. However, I particularly interested in an efficient way of converting List<Integer>to int[]

我知道这里描述一个解决方案。但是,我对转换List<Integer>为的有效方式特别感兴趣int[]

采纳答案by T.J. Crowder

Given the need to convert from Integerto int, I don't think you're going to find something more efficient than what you have, if I assume you're talking about runtime efficiency.

鉴于从需要转换Integerint,我不认为你会找到的东西比你有什么更有效的,如果我假设你在谈论执行效率。

You mightfind converting to Integer[]first and then looping might be more efficient (below), but you might not, too. You'd have to test it in your specific scenario and see.

可能会发现先转换为Integer[]然后循环可能更有效(见下文),但您也可能不会。您必须在您的特定场景中对其进行测试并查看。

Here's that example:

这是那个例子:

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];
}

回答by Donald Raab

If efficiency is your primary concern, I think you can use your solution and make it more efficient by using an indexed for loop on the listResult if it is RandomAccess. However this makes the code much less readable, and you'd have to benchmark it for your use cases to see if it is more efficient.

如果效率是您的主要关注点,我认为您可以使用您的解决方案,并通过在 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;
}

If you use Java 8 and would like to write less code you can use the Streams library.

如果您使用 Java 8 并希望编写更少的代码,则可以使用 Streams 库。

List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
int[] array = list.stream().mapToInt(i -> i).toArray();

If you are open to using a third party library, you can Eclipse Collectionsas follows.

如果您愿意使用第三方库,您可以按如下方式使用Eclipse Collections

MutableList<Integer> list = Lists.mutable.with(1, 2, 3, 4, 5);
int[] array = list.collectInt(i -> i).toArray();

The following is slightly more code, but is the most efficient solution I could come up with using Eclipse Collections.

下面是稍微多一些的代码,但它是我使用 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);

If you need to use the java.util.Listinterface, the ListIterateutility class can be used from Eclipse Collections.

如果您需要使用该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);

The ListIterateutility will use different iteration code for RandomAccesslists and non-RandomAccesslists.

ListIterate实用程序将对RandomAccess列表和非RandomAccess列表使用不同的迭代代码。

The most efficient thing to do would be to change the List<Integer>to a MutableIntListin Eclipse Collections or another library that has support for primitive collections.

最有效的事情是改变了List<Integer>一个MutableIntList在Eclipse集合或已经对元数据集合的支持另一个库。

Note: I am a committer for Eclipse Collections.

注意:我是 Eclipse Collections 的提交者。

回答by Saxintosh

In Java 8:

在 Java 8 中:

int[] anArray = list.stream()
                    .filter(Objects::nonNull)
                    .mapToInt(Integer::intValue)
                    .toArray();

回答by olajide

There is efficient way you could do this Java. However, this could open room for someone to create the generic function (depend on demand).

有一种有效的方法可以执行此 Java。但是,这可能为某人创建通用功能(取决于需求)打开空间。

Just like this sample i wrote, I suggest you do the same to the specific knowledge of your program.

就像我写的这个示例一样,我建议你对你的程序的特定知识做同样的事情。

    // 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;
    }