Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert an array of primitive longs into a List of Longs

Since Java 8 you can now use streams for that:

long[] arr = { 1, 2, 3, 4 };
List<Long> list = Arrays.stream(arr).boxed().collect(Collectors.toList());

I found it convenient to do using apache commons lang ArrayUtils (JavaDoc, Maven dependency)

import org.apache.commons.lang3.ArrayUtils;
...
long[] input = someAPI.getSomeLongs();
Long[] inputBoxed = ArrayUtils.toObject(input);
List<Long> inputAsList = Arrays.asList(inputBoxed);

it also has the reverse API

long[] backToPrimitive = ArrayUtils.toPrimitive(objectArray);

EDIT: updated to provide a complete conversion to a list as suggested by comments and other fixes.


import java.util.Arrays;
import org.apache.commons.lang.ArrayUtils;

List<Long> longs = Arrays.asList(ArrayUtils.toObject(new long[] {1,2,3,4}));

hallidave and jpalecek have the right idea—iterating over an array—but they don't take advantage of a feature provided by ArrayList: since the size of the list is known in this case, you should specify it when you create the ArrayList.

List<Long> list = new ArrayList<Long>(input.length);
for (long n : input)
  list.add(n);

This way, no unnecessary arrays are created only to be discarded by the ArrayList because they turn out to be too short, and no empty "slots" are wasted because ArrayList overestimated its space requirements. Of course, if you continue to add elements to the list, a new backing array will be needed.


A bit more verbose, but this works:

    List<Long> list = new ArrayList<Long>();
    for (long value : input) {
        list.add(value);
    }

In your example it appears that Arrays.asList() is interpreting the input as list of long[] arrays instead of a list of Longs. A bit surprising, for sure. Autoboxing just doesn't work the way you want it to in this case.