tl;dr
Use Unicode code points rather than char
, as a best practice.
"1234567890"
.codePoints()
.map(
( int codePoint ) -> Integer.parseInt( Character.toString( codePoint ) )
)
.boxed()
.toList()
[1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
char
obsolete
The char
type is obsolete, unable to represent even half of the characters defined in Unicode. While this type would work for strictly Arabic numerals, we should make a habit of using code point integer numbers rather than char
type values.
IntStream
of code points
The easiest way to work with text as code point numbers is to call String#codePoints
to get an IntStream
, a stream of int
primitive values. For digit 1
, we get code point 49, for digit 2
code point 50, and so on, with 0
being assigned to code point 48.
For each int
representing a code point number, convert to the character assigned to that number as a String
object. So 49 becomes "1", 50 becomes "2", and so on.
Then parse each digit-as-string into an int
value for the digit value. Throws a NumberFormatException
if the string is not a parsable integer.
By calling .boxed
, we convert each int
primitive for the digit to an Integer
object.
Lastly, we collect the Integer
objects representing each digit into an unmodifiable List
. The Stream#toList
method is new in Java 16. For earlier Java, use .collect( Collectors.toList() )
.
List < Integer > digits =
"1234567890"
.codePoints()
.map( codePoint -> Integer.parseInt( Character.toString( codePoint ) ) )
.boxed()
.toList();
Here is a full working example class with main
method.
package work.basil.demo.text;
import java.util.List;
public class App2
{
public static void main ( String[] args )
{
List < Integer > digits =
"1234567890"
.codePoints()
.map( codePoint -> Integer.parseInt( Character.toString( codePoint ) ) )
.boxed()
.toList();
System.out.println( "digits = " + digits );
}
}
When run.
digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]