Converting Array of Primitives to Array of Containers in Java

Apache Commons

Apache Commons / Lang has a class ArrayUtils that defines these methods.

  • All methods called toObject(...)
    convert from primitive array to wrapper array
  • All called toPrimitive(...) convert
    from wrapper object array to
    primitive array

Example:

final int[]     original        = new int[] { 1, 2, 3 };
final Integer[] wrappers        = ArrayUtils.toObject(original);
final int[]     primitivesAgain = ArrayUtils.toPrimitive(wrappers);
assert Arrays.equals(original, primitivesAgain);

Guava

But then I’d say that Arrays of wrapped primitives are not very useful, so you might want to have a look at Guava instead, which provides Lists of all numeric types, backed by primitive arrays:

List<Integer> intList = Ints.asList(1,2,3,4,5);
List<Long> longList   = Longs.asList(1L,2L,3L,4L,5L);
// etc.

The nice think about these array-backed collections is that

  1. they are live views (i.e. updates to the array change the list and vice-versa)
  2. the wrapper objects are only created when needed (e.g. when iterating the List)

See: Guava Explained / Primitives


Java 8

On the other hand, with Java 8 lambdas / streams, you can make these conversions pretty simple without using external libraries:

int[] primitiveInts = {1, 2, 3};
Integer[] wrappedInts = Arrays.stream(primitiveInts)
                              .boxed()
                              .toArray(Integer[]::new);
int[] unwrappedInts = Arrays.stream(wrappedInts)
                             .mapToInt(Integer::intValue)
                             .toArray();
assertArrayEquals(primitiveInts, unwrappedInts);

double[] primitiveDoubles = {1.1d, 2.2d, 3.3d};
Double[] wrappedDoubles = Arrays.stream(primitiveDoubles)
                                .boxed()
                                .toArray(Double[]::new);
double[] unwrappedDoubles = Arrays.stream(wrappedDoubles)
                                  .mapToDouble(Double::doubleValue)
                                  .toArray();

assertArrayEquals(primitiveDoubles, unwrappedDoubles, 0.0001d);

Note that the Java 8 version works for int, long and double, but not for byte, as Arrays.stream() only has overloads for int[], long[], double[] or a generic object T[].

Leave a Comment