Issue
I want to convert a primitive Java integer value:
int myInt = 4821;
To an integer array:
int[] myInt = {4, 8, 2, 1};
Solution
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.
Answered By - Arvind Kumar Avinash Answer Checked By - Mary Flores (PHPFixing Volunteer)
0 Comments:
Post a Comment
Note: Only a member of this blog may post a comment.