I want to convert a primitive Java integer value:
int myInt = 4821;
To an integer array:
int[] myInt = {4, 8, 2, 1};
There can be so many ways to do it. A concise way of doing it's using Stream
API as shown below:
import java.util.Arrays;
public class Main {
public static void main(String[] args) {
int myInt = 4821;
int[] arr =
String.valueOf(Math.abs(myInt)) // Convert the absolute value to String
.chars() // Get IntStream out of the String
.map(c -> c - 48) // Convert each char into numeric value
.toArray(); // Convert the stream into array
// Display the array
System.out.println(Arrays.toString(arr));
}
}
Output:
[4, 8, 2, 1]
Notes:
'0'
is 48
, that of '1'
is 49
and so on.Math#abs
returns the absolute value of an int
value
Math.abs(-5) = 5
and Math.abs(5) = 5