Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting Array of Primitives to Array of Containers in Java

Tags:

java

arrays

Is there an elegant way to turn an array of primitives into an array of the corresponding container objects -- turn a byte[] into a Byte[], for example? Or am I stuck with looping through it and doing it manually?

Yeah, the for loop isn't exactly difficult. Just kinda ugly.

like image 513
BlairHippo Avatar asked Sep 22 '10 14:09

BlairHippo


People also ask

How do you convert a primitive type array to a wrapper class?

To do that, we will simply iterate through the primitive array and use autoboxing to convert each element to the respective wrapper object type. Similarly, we can use iteration along with unboxing to convert an array of wrapper objects to an array of primitives.

What is the best way to convert a primitive array to a List in Java 8?

Since Java 8, we can use the Stream API. We can provide a one-line solution using a Stream: int[] input = new int[]{1,2,3,4}; List<Integer> output = Arrays. stream(input). boxed().

What is array of primitives?

Arrays of primitives have elements that are initialized to default values. Arrays of objects have the value null in each element. You are practically guaranteed to have a related question on the exam.


2 Answers

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[].

like image 155
Sean Patrick Floyd Avatar answered Sep 20 '22 17:09

Sean Patrick Floyd


You have to loop through your array.


Updated after @seanizer answer :

Basically the toObject(byte[] array) method will do the looping for you :

public static Byte[] toObject(byte[] array) {     if (array == null) {         return null;     } else if (array.length == 0) {         return EMPTY_BYTE_OBJECT_ARRAY;     }     final Byte[] result = new Byte[array.length];     for (int i = 0; i < array.length; i++) {         result[i] = new Byte(array[i]);     }     return result; } 

And unless you will really use the commons lang lib, you should simply reuse this method and avoid a useless dependency (IMHO).

like image 22
Colin Hebert Avatar answered Sep 20 '22 17:09

Colin Hebert