I need to convert comma separated string to list of integers. For example if I have following string
String numbersArray = \"1, 2, 3, 5, 7, 9,\";
I think below piece of code could be helpful for you.
import java.util.Scanner;
public class Solution {
public static void main(String[] args) throws java.io.IOException {
String numbersArray = "1, 2, 3, 5, 7, 9,";
System.out.println(numbersArray);
Scanner sc = new Scanner(numbersArray);
sc.useDelimiter("(, *)*");
try{
while(true){
System.out.println(sc.nextInt());
}
} catch (Exception e) {
System.out.println("reading is completed");
}
}
}
Instead of using System.out.println add it to the Integer list.
Here we are not traversing through the complete list multiple times, instead we traverse only once and storing them in array.