0

I'm struggling with finding an efficient way to split the digits of a number into a list.

For example, for the number:

23464646237

and the

ArrayList <Integer> vector;

i want to insert in each position of the array, a digit from the number, therefore obtaining the following output:

vector = {2,3,4,6,4,6,4,6,2,3,7}

How can i do this in a clean and efficient way in Java ?

Thanks in advance

laker001
  • 417
  • 7
  • 20

5 Answers5

2

The parseInt is not needed,

for(int i = 0; i < numberAsString.length(); i++)
    vector.add((int)numberAsString.charAt(i) - 48);

This will retrieve the ASCII value of the number at the position, then subtract 48 which is the value of 0 in the table.

Number from -127 to 127 are cached so I believe this will be the most efficient method (note that I'm not 100% sure). But anyway, only tried to give a way saving the parseInt call as you asked for the most efficient.

Jean-François Savard
  • 20,626
  • 7
  • 49
  • 76
2

First of all don't convert it to string. Because it will work faster with numeric values. So you can use:

long nr = 23464646237;
while (nr > 0)
{
    vector.add(nr % 10);
    nr /= 10;
}
bmavus
  • 892
  • 1
  • 7
  • 21
2

You could do something like this:

List<Integer> vector = Arrays.asList(String.valueOf(number).split(""))
            .stream()
            .map(Integer::parseInt)
            .collect(Collectors.toList());
kjosh
  • 587
  • 4
  • 11
2

Just make your number a string and make use of the charAt() method to add each char of the string into a List.

public static ArrayList<Object>vect=new ArrayList<Object>();


public static void main(String[] args){
    String y="123321312312";
    for (int i=0;i<y.length();i++){
        vect.add(y.charAt(i));
    }
}
Theo
  • 1,165
  • 9
  • 14
1

Try this:

long yourNumber = 23464646237L;
ArrayList<Integer> vector = new ArrayList<Integer>();
String numStr = String.valueOf(yourNumber);
for(int i=0;i<numStr.length();i++)
{
    vector.add(Integer.valueOf(numStr.charAt(i)));
}
Dermot Blair
  • 1,600
  • 10
  • 10