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

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.

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.

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 Collections as follows.

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.

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.List interface, the ListIterate utility class can be used from Eclipse Collections.

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 ListIterate utility will use different iteration code for RandomAccess lists and non-RandomAccess lists.

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

Note: I am a committer for Eclipse Collections.


Given the need to convert from Integer to 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.

You might find 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.

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

In Java 8:

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

Tags:

Java

Arrays

List