How to change a string of numbers, spaces, and commas, to an arraylist of integers

I want to figure out how to take a string of numbers, spaces, and commas, and turn it into an arraylist of integers.

For example, the input is 1, 2, 3, 4, 11, 23 and the output would be an arraylist containing those same numbers but in integer form instead of a string.

I’ve experimented with some code to remove the spaces and commas then add the numbers to an arraylist but I just can’t seem to get my if statements to work. Feel free to change anything about the nature of the input or anything like that, it is very flexible. Here is the important bit of what I have now if it helps;

numCheck = Kd.nextLine();
        for(int i = 1; i < numCheck.length(); i++) {
            if(String.valueOf(numCheck.charAt(1)) == " ") {
                num = numCheck.charAt(0);
                System.out.println(num+"a");
                nums.add(num);  
                break;
            }
            else if((String.valueOf(numCheck.charAt(i-1))) == " "){//1 2 34
                    num = numCheck.charAt(i);
                    System.out.println(num + "b");
                    nums.add(num);  
                    i+=1;

                }
            else if(String.valueOf(numCheck.charAt(i-1)) != " ")
                {
                    numsTogether = numCheck.charAt(i-1) + "" + numCheck.charAt(i);
                    System.out.println(numsTogether + "c");
                    nums.add(Integer.parseInt(numsTogether));
                    i++;
                }   

Any help is appreciated, Thanks.

Answer

You can achieve this in one line by using java 8 streams using String.trim() will trim all the spaces and Integer.valueOf() change string to Integer

List<Integer> l= Arrays.stream("1, 2, 3, 4, 11, 23".split(",")).map(item->Integer.valueOf(item.trim())).collect(Collectors.toList());
    System.out.println(l);

Leave a Reply

Your email address will not be published. Required fields are marked *