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[].
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[].
Since int[] is a class, it can be used to declare variables. For example, int[] list; creates a variable named list of type int[].
You can use Java 8 Stream
s:
If the input array has no null
s:
Integer[] integerArr = ...
int[] arr = Arrays.stream(integerArr).mapToInt(Integer::intValue).toArray();
And with handling of null
s:
Integer[] integerArr = ...
int[] arr = Arrays.stream(integerArr).mapToInt(i -> i != null ? i : 0).toArray();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With