I want to convert a primitive Java integer value:
int myInt = 4821;
To an integer array:
int[] myInt = {4, 8, 2, 1};
Advertisement
Answer
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:
- ASCII value of
'0'
is48
, that of'1'
is49
and so on. Math#abs
returns the absolute value of anint
value- e.g.
Math.abs(-5) = 5
andMath.abs(5) = 5
- e.g.