Tuesday, March 29, 2016

Java, how to onvert primitive array type to Boxed type, convert int array to Integer array

With Java 8's functional interfaces, one could be more concise and use shorter codes to convert a primitive array to the corresponding boxed type. Below we will use int array and Integer array as an example.

Prior to Java 8, we could use a few ways below to copy from the primitive array to a new array of the same length but of the boxed type:


int[] old = {1,2,3,4,5};
Integer[] newArray = new Integer[old.length];
int i = 0;
for (int value : oldArray) {
    newArray[i++] = Integer.valueOf(value);
}

// or Arrays.copyOf()

System.arraycopy(old, 0, newArray, 0, old.length);


With java 8, we could use the stream interface and lambda expressions as below.

int[] old = {1,2,3,4,5};
Integer[] newArray = IntStream.of(old).boxed()
                     .toArray(Integer[]::new);

// or

newArray = Arrays.stream(old).boxed()
                 .toArray(Integer[]::new);

Alternatively, for ease of printing the array out, one could also collect it to a list after the stream operations.

int[] old = {1,2,3,4,5};

List<integer> newArrayList = IntStream.of(old).boxed()
                        .collect(Collectors.toList());
System.out.println(newArrayList);

The output will be:

[1, 2, 3, 4, 5]

No comments: