antohoho
antohoho

Reputation: 1020

Convert Integer[] to Long[] in Java

I am looking for the most efficient and hopefully without loops method to convert an array of integers to an array of longs.

I was hoping to do something like this

Arrays.asList(ids).toArray(new Long(ids.length));

but it won't work.

Upvotes: 1

Views: 1135

Answers (2)

bhspencer
bhspencer

Reputation: 13570

Just write it your self. Its really not so bad.

public static Long[] toLongArray(Integer[] ints) {
    Long[] result = new Long[ints.length];
    for (int i = 0; i < ints.length; i++) {
        result[i] = Long.valueOf(ints[i]);
    }
    return result;
}

Upvotes: 2

Pshemo
Pshemo

Reputation: 124235

This looks pretty clean to me.

Stream.of(ids).map(Long::valueOf).toArray(Long[]::new);

Upvotes: 3

Related Questions