Convert an array of primitive longs into a List of Longs

Brandon Yarbrough picture Brandon Yarbrough · Apr 16, 2009 · Viewed 92k times · Source

This may be a bit of an easy, headdesk sort of question, but my first attempt surprisingly completely failed to work. I wanted to take an array of primitive longs and turn it into a list, which I attempted to do like this:

long[] input = someAPI.getSomeLongs();
List<Long> inputAsList = Arrays.asList(input); //Total failure to even compile!

What's the right way to do this?

Answer

Eran Medan picture Eran Medan · Dec 29, 2009

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.