Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

arrays

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

like image 499
afzalex Avatar asked Jun 20 '18 07:06

afzalex


People also ask

How do you convert a number to an int array?

int temp = test; ArrayList<Integer> array = new ArrayList<Integer>(); do{ array. add(temp % 10); temp /= 10; } while (temp > 0); This will leave you with ArrayList containing your digits in reverse order. You can easily revert it if it's required and convert it to int[].

What does int [] do in Java?

Since int[] is a class, it can be used to declare variables. For example, int[] list; creates a variable named list of type int[].


1 Answers

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();
like image 119
Eran Avatar answered Nov 03 '22 02:11

Eran