Convert an array of primitive longs into a List of

2019-01-01 09:18发布

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?

15条回答
谁念西风独自凉
2楼-- · 2019-01-01 09:39

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());
查看更多
浮光初槿花落
3楼-- · 2019-01-01 09:39

If you want similar semantics to Arrays.asList then you'll need to write (or use someone else's) customer implementation of List (probably through AbstractList. It should have much the same implementation as Arrays.asList, only box and unbox values.

查看更多
余生无你
4楼-- · 2019-01-01 09:40

No, there is no automatic conversion from array of primitive type to array of their boxed reference types. You can only do

long[] input = someAPI.getSomeLongs();
List<Long> lst = new ArrayList<Long>();

for(long l : input) lst.add(l);
查看更多
登录 后发表回答