I have numbers like 1100, 1002, 1022 etc. I would like to have the individual digits, for example for the first number 1100 I want to have 1, 1, 0, 0.
How can I get it in Java?
I have numbers like 1100, 1002, 1022 etc. I would like to have the individual digits, for example for the first number 1100 I want to have 1, 1, 0, 0.
How can I get it in Java?
How about this?
or instead of printing to the console, we can collect it in an array of integers and then print the array:
Since I don't see a method on this question which uses Java 8, I'll throw this in. Assuming that you're starting with a
String
and want to get aList<Integer>
, then you can stream the elements like so.This gets the characters in the
String
as aIntStream
, maps those integer representations of characters to a numeric value, and then collects them into a list.I think this will be the most useful way to get digits:
Then you can get digits in a simple way:
or more simply:
Notice the last method calls getDigitsOf method too much time. So it will be slower. You should create an int array and then call the getDigitsOf method once, just like in second code block.
In the following code, you can reverse to process. This code puts all digits together to make the number:
Both methods I have provided works for negative numbers too.
I noticed that there are few example of using Java 8 stream to solve your problem but I think that this is the simplest one:
To be clear: You use
String.valueOf(number)
to convert int to String, thenchars()
method to get an IntStream (each char from your string is now an Ascii number), then you need to runmap()
method to get a numeric values of the Ascii number. At the end you usetoArray()
method to change your stream into an int[] array.