Convert an Array of Primitive Longs into a List of Longs

Convert an array of primitive longs into a List of Longs

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.

Converting an array of long to ArrayList Long

Using ArrayUtils from apache commons-lang

long[] longs = new long[]{1L};
Long[] longObjects = ArrayUtils.toObject(longs);
List<Long> longList = java.util.Arrays.asList(longObjects);

Long[] to long[] and vice versa?

There is no better way than loop and copy

The best solution is to avoid converting in the first place. If you are worries about efficiency avoid using Long[] as it is many times larger than long[] If you need to use a collection you can try TLongArrayList which wraps a long[].

What is the best way of converting List Long object to long[] array in java?

Since Java 8, you can do the following:

long[] result = values.stream().mapToLong(l -> l).toArray();

What's happening here?

  1. We convert the List<Long> into a Stream<Long>.
  2. We call mapToLong on it to get a LongStream
    • The argument to mapToLong is a ToLongFunction, which has a long as the result type.
    • Because Java automatically unboxes a Long to a long, writing l -> l as the lambda expression works. The Long is converted to a long there. We could also be more explicit and use Long::longValue instead.
  3. We call toArray, which returns a long[]

How to reduce the number of casts when converting a primitive array to a boxed array

Using a Map we can implement a solution which doesn't use if at all.

public class Boxing {

private static final Map<Class<?>, Function> MAPPER = createMapper();

private static Map<Class<?>, Function> createMapper() {
Map<Class<?>, Function> mapper = new HashMap<>();
mapper.put(int[].class, toBoxedIntArray());
mapper.put(long[].class, toBoxedLongArray());
// TODO put mapping functions for remaining primitive array types
return mapper;
}

@SuppressWarnings("unchecked")
public static <T> T[] toBoxedArray(Object array) {
if (array == null || !array.getClass().isArray() || !array.getClass().getComponentType().isPrimitive()) {
return null;
}

return (T[]) MAPPER.get(array.getClass()).apply(array);
}

private static Function<int[], Integer[]> toBoxedIntArray() {
return array -> {
Integer[] boxed = new Integer[array.length];
Arrays.setAll(boxed, index -> Integer.valueOf(array[index]));
return boxed;
};
}

private static Function<long[], Long[]> toBoxedLongArray() {
return array -> {
Long[] boxed = new Long[array.length];
Arrays.setAll(boxed, index -> Long.valueOf(array[index]));
return boxed;
};
}

// TODO implement mapping functions for remaining primitive array types

public static <T> List<T> castArrayToList(Object array) {
T[] boxedArray = toBoxedArray(array);
return boxedArray != null ?
Arrays.asList(boxedArray) :
null;
}

public static List castArrayToList(Collection collection) {
return new ArrayList<>(collection);
}

}

This can be used as follows for example:

  public static void main(String[] args) {
int[] intArr = new int[] { 0, 1, 2 };
Integer[] boxed = toBoxedArray(intArr);
System.out.println(boxed); // [Ljava.lang.Integer;34340fab
System.out.println(toBoxedArray(boxed)); // null
System.out.println(castArrayToList(intArr)); // [0, 1, 2]
System.out.println(castArrayToList(boxed)); // null
}

Using the class as key of the MAPPER-Map works like an instanceof and replaces therefore the bunch of if-statements.

Please note that there are two methods castArrayToList. One which is intended to process primitive arrays and an additional one which takes a Collection. I added the latter one to reflect the behavior of castArrayToList shown in the question which will return a List if the given object is a Collection.

For the sake of completeness: Another way to literally get rid of if would be to use a switch-statement on array.getClass().getSimpleName(). But the resulting method would be similar bulky.

Is it possible to convert ArrayList Integer into ArrayList Long ?

Not in a 1 liner.

List<Integer> ints = Arrays.asList(1,2,3,4,5,6,7,8,9);
int nInts = ints.size();
List<Long> longs = new ArrayList<Long>(nInts);
for (int i=0;i<nInts;++i) {
longs.add(ints.get(i).longValue());
}

// Or you can use Lambda expression in Java 8

List<Integer> ints = Arrays.asList(1,2,3,4,5,6,7,8,9);
List<Long> longs = ints.stream()
.mapToLong(Integer::longValue)
.boxed().collect(Collectors.toList());

Convert an int array to long array using Java 8?

You need to use the mapToLong operation.

int[] intArray = {1, 2, 3};
long[] longArray = Arrays.stream(intArray).mapToLong(i -> i).toArray();

or, as Holger points out, in this case, you can directly use asLongStream():

int[] intArray = {1, 2, 3};
long[] longArray = Arrays.stream(intArray).asLongStream().toArray();

The map method on primitive streams return a stream of the same primitive type. In this case, IntStream.map will still return an IntStream.

The cast to long with

.map(item -> ((long) item))

will actually make the code not compile since the mapper used in IntStream.map is expected to return an int and you need an explicit cast to convert from the new casted long to int.

With .mapToLong(i -> i), which expects a mapper returning a long, the int i value is promoted to long automatically, so you don't need a cast.



Related Topics



Leave a reply



Submit