What is the best way to convert Integer[] to int[]

afzalex :

What is the best way to convert Integer array to int array.

The simple solution for it would be :

public int[] toPrimitiveInts(Integer[] ints) {
    int[] primitiveInts = new int[ints.length];
    for(int i = 0; i < ints.length; i++) {
        primitiveInts[i] = ints[i] == null ? 0 : ints[i];
    }
    return primitiveInts;
}

In the above example I taken 0 for null values for the fact that default value for objects/wrappers is null and for int is 0.

This answer shows how to convert int[] to Integer[]

But I don't find an easy way to convert Integer[] to int[].

Eran :

You can use Java 8 Streams:

If the input array has no nulls:

Integer[] integerArr = ...
int[] arr = Arrays.stream(integerArr).mapToInt(Integer::intValue).toArray();

And with handling of nulls:

Integer[] integerArr = ...
int[] arr = Arrays.stream(integerArr).mapToInt(i -> i != null ? i : 0).toArray();

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=459809&siteId=1