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:21

You can use transmorph :

Transmorph transmorph = new Transmorph(new DefaultConverters());
List<Long> = transmorph.convert(new long[] {1,2,3,4}, new TypeReference<List<Long>>() {});

It also works if source is an array of ints for example.

查看更多
流年柔荑漫光年
3楼-- · 2019-01-01 09:22

As another possibility, the Guava library provides this as Longs.asList(), with similar utility classes for the other primitive types.

import com.google.common.primitives.Longs;

long[] input = someAPI.getSomeLongs();
List<Long> output = Longs.asList(input);
查看更多
春风洒进眼中
4楼-- · 2019-01-01 09:23

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.

查看更多
唯独是你
5楼-- · 2019-01-01 09:24

Another way with Java 8.

final long[] a = new long[]{1L, 2L};
final List<Long> l = Arrays.stream(a).boxed().collect(Collectors.toList());
查看更多
余欢
6楼-- · 2019-01-01 09:28

I know this question is old enough, but... you can also write your own conversion method:

@SuppressWarnings("unchecked")
public static <T> List<T> toList(Object... items) {

    List<T> list = new ArrayList<T>();

    if (items.length == 1 && items[0].getClass().isArray()) {
        int length = Array.getLength(items[0]);
        for (int i = 0; i < length; i++) {
            Object element = Array.get(items[0], i);
            T item = (T)element;
            list.add(item);
        }
    } else {
        for (Object i : items) {
            T item = (T)i;
            list.add(item);
        }
    }

    return list;
}

After you include it using static import, possible usages could be:

    long[] array = { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
    List<Long> list = toList(array);

or

    List<Long> list = toList(1l, 2l, 3l, 4l, 5l, 6l, 7l, 8l, 9l);
查看更多
听够珍惜
7楼-- · 2019-01-01 09:29
import java.util.Arrays;
import org.apache.commons.lang.ArrayUtils;

List<Long> longs = Arrays.asList(ArrayUtils.toObject(new long[] {1,2,3,4}));
查看更多
登录 后发表回答